- move your sum inside the loop
- increment your summation variable
Finding sum of for loop with if else statement
3 ビュー (過去 30 日間)
古いコメントを表示
trangeF = 0:0.001:1.6; % Time range
init = 0;
for n = -2:2
if n == 0
s0 = 312.5.*((-0.08481.*1j.*exp(-0.08481.*1j.*n)/-7.8539.*1j.*n)-((-7.8539.*1j.*n)/(-61.6837.*(n^2)+400)).*(exp(-0.08481.*1j.*n)-1));
xt = (s0).*(exp(7.8539.*1j.*n.*trangeF));
else
s1 = 312.5.*(((exp(-0.08481.*1j.*n)-1)/-7.8539.*1j.*n)-(((-7.8539.*1j.*n)/(-61.6837.*(n^2)+400)).*(exp(-0.08481.*1j.*n)-1)));
xt = (s1).*(exp(7.8539.*1j.*n.*trangeF));
end
end
sums = init + xt;
plot(trangeF, sums,'b')
I am trying to find the sum of the loop. I know I am supposed to have a variable that initializes to 0, then each time I step thrpugh the loop, I add the term to the initialized variable. Am I setting this up correctly?
0 件のコメント
回答 (2 件)
Fabio Freschi
2023 年 10 月 20 日
You must
Note that your vector is complex and plot displays only the real part
trangeF = 0:0.001:1.6; % Time range
% initialization
sums = zeros(size(trangeF));
for n = -2:2
if n == 0
s0 = 312.5.*((-0.08481.*1j.*exp(-0.08481.*1j.*n)/-7.8539*1j)-((-7.8539.*1j.*n)/(-61.6837.*(n^2)+400)).*(exp(-0.08481.*1j.*n)-1));
xt = (s0).*(exp(7.8539.*1j.*n.*trangeF));
else
s1 = 312.5.*(((exp(-0.08481.*1j.*n)-1)/-7.8539.*1j.*n)-(((-7.8539.*1j.*n)/(-61.6837.*(n^2)+400)).*(exp(-0.08481.*1j.*n)-1)));
xt = (s1).*(exp(7.8539.*1j.*n.*trangeF));
end
% sum in the loop
sums = sums + xt;
end
figure
plot(trangeF, sums,'b')
0 件のコメント
Torsten
2023 年 10 月 20 日
You mean this ?
trangeF = 0:0.001:1.6; % Time range
xt = zeros(size(trangeF));
for n = -2:2
if n == 0
s0 = 312.5.*((-0.08481.*1j.*exp(-0.08481.*1j.*n)/-7.8539*1j)-((-7.8539.*1j.*n)/(-61.6837.*(n^2)+400)).*(exp(-0.08481.*1j.*n)-1));
xt = xt + (s0).*(exp(7.8539.*1j.*n.*trangeF));
else
s1 = 312.5.*(((exp(-0.08481.*1j.*n)-1)/-7.8539.*1j.*n)-(((-7.8539.*1j.*n)/(-61.6837.*(n^2)+400)).*(exp(-0.08481.*1j.*n)-1)));
xt = xt + (s1).*(exp(7.8539.*1j.*n.*trangeF));
end
end
plot(trangeF, [real(xt);imag(xt)],'b')
0 件のコメント
参考
カテゴリ
Help Center および File Exchange で Loops and Conditional Statements についてさらに検索
製品
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!