Finding sum of for loop with if else statement

3 ビュー (過去 30 日間)
Yamana Uno
Yamana Uno 2023 年 10 月 20 日
回答済み: Torsten 2023 年 10 月 20 日
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?

回答 (2 件)

Fabio Freschi
Fabio Freschi 2023 年 10 月 20 日
You must
  1. move your sum inside the loop
  2. increment your summation variable
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')
Warning: Imaginary parts of complex X and/or Y arguments ignored.

Torsten
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')

カテゴリ

Help Center および File ExchangeLoops and Conditional Statements についてさらに検索

製品

Community Treasure Hunt

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

Start Hunting!

Translated by