Adding k discrete functions together in a "for" loop
조회 수: 3 (최근 30일)
이전 댓글 표시
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
채택된 답변
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
추가 답변 (0개)
참고 항목
카테고리
Help Center 및 File Exchange에서 Symbolic Math Toolbox에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!