Finding sum of for loop with if else statement

4 次查看(过去 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?

回答(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 CenterFile Exchange 中查找有关 Loops and Conditional Statements 的更多信息

产品

Community Treasure Hunt

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

Start Hunting!

Translated by