Filter löschen
Filter löschen

Finding sum of for loop with if else statement

9 Ansichten (letzte 30 Tage)
Yamana Uno
Yamana Uno am 20 Okt. 2023
Beantwortet: Torsten am 20 Okt. 2023
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?

Antworten (2)

Fabio Freschi
Fabio Freschi am 20 Okt. 2023
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 am 20 Okt. 2023
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')

Kategorien

Mehr zu Loops and Conditional Statements finden Sie in Help Center und File Exchange

Produkte

Community Treasure Hunt

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

Start Hunting!

Translated by