Adding k discrete functions together in a "for" loop

3 ビュー (過去 30 日間)
Shawn Cooper
Shawn Cooper 2019 年 12 月 1 日
回答済み: Vladimir Sovkov 2019 年 12 月 1 日
Hello,
I'm trying to create a loop that creates individual discrete sine waves from a vector of sampled frequencies (locs), then adds those values together to create a single combined waveform.
My code worked well symbolically:
syms tau
locs = [440 529 630] %example frequencies
combined = 0;
for k = 1:length(locs)
figure
hold on
wave(k) = sin(2*pi*locs(k)*tau); %generate sin wave for each sampled frequency
fplot(sin(2*pi*locs(k)*tau),[0 0.01])
hold off
combined = combined + wave(k); %add each generated sin wave to the previous one
end
figure
fplot(combined, [0 0.01])
But I am having trouble converting it to a discrete form. I get an error that says the indices on the left do not match the indices on the right, which I assume means that I am trying to put a 132300 element array (the sin function of t) into a 1x3 array (wave(k)).
t = 0:1/44100:3;
locs = [440 529 630] %example frequencies
combined = 0;
for k = 1:length(locs)
figure
hold on
wave(k) = sin(2*pi*locs(k)*t); %generate sin wave for each sampled frequency
stem(sin(2*pi*locs(k)*t),[0 441])
hold off
combined = combined + wave(k); %add each generated sin wave to the previous one
end
figure
stem(combined, [0 441])
Is there a better way to handle/store each of the generated sin waves so they can be added together in a discrete form?

採用された回答

Vladimir Sovkov
Vladimir Sovkov 2019 年 12 月 1 日
If you do not need the "wave" contents for a further use, just drop out (k) from all its entries.
If you need it for a further use, initialize it as
wave=zeros(3,numel(t));
before the loop and address it as wave(k,:) within the loop.
Commands "stem" are definitely incorrect. If you want to see plots of the dependences on t, they should look something like stem(t,combined) or plot(t,combined), etc. However, the t range in the second version (0,3) is much wider than the one of the first version (0,0.01): consequently, such a graph will show much (hugely) more oscillations--you will probably see nothing but a unifromly painted square.
I do not see any need in the "nold on" and "hold off" commands in the both version.

その他の回答 (0 件)

カテゴリ

Help Center および File ExchangeSymbolic Math Toolbox についてさらに検索

製品


リリース

R2019b

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by