Adding k discrete functions together in a "for" loop
4 Ansichten (letzte 30 Tage)
Ältere Kommentare anzeigen
Shawn Cooper
am 1 Dez. 2019
Beantwortet: Vladimir Sovkov
am 1 Dez. 2019
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?
0 Kommentare
Akzeptierte Antwort
Vladimir Sovkov
am 1 Dez. 2019
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 Kommentare
Weitere Antworten (0)
Siehe auch
Kategorien
Mehr zu Symbolic Math Toolbox finden Sie in Help Center und File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!