필터 지우기
필터 지우기

Finding sum of for loop with if else statement

조회 수: 6 (최근 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 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