For loop with two conditions
조회 수: 3 (최근 30일)
이전 댓글 표시
I need to create a for loop that runs from n=-2 to 2. When n=0, I must use a different equation (D_n_0) to plot the result. When n=-2,-1,1,2 I will use another equation (D_n) to plot the result.
How do I set up a foot loop that allows for a different equation when n=0 but not for other values?
Thank you!
댓글 수: 1
채택된 답변
Voss
2023년 10월 19일
for n = -2:2
if n == 0
% use D_n_0
else
% use D_n
end
end
댓글 수: 2
Voss
2023년 10월 19일
편집: Voss
2023년 10월 19일
t is a scalar, so you're only ever plotting one point each time, which you won't see without a data marker. Check that the t I used below is something like you intended.
hold off in the else block makes subsequent plotted lines replace what was already plotted, so I changed it to hold on.
hold on in the if block is not necessary because that block is only executed one time (when n == 0), so only one line is being plotted, so I removed that (and I assumed that plot should be in another subplot).
"the command window says imginary parts of complex X and Y ignored"
For plotting complex numbers you may want to plot the magnitude and phase separately.
t = linspace(0,0.8,100);
for n = -2:2
if n == 0
D_n_0 = 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));
xt0 = (D_n_0).*(exp(7.8539.*1j.*n.*t));
subplot(2,1,2)
plot(t,xt0)
else
D_n = 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 = (D_n).*(exp(7.8539.*1j.*n.*t));
subplot(2,1,1)
plot(t,xt)
hold on
title('Exponential Fourier Series')
end
end
추가 답변 (0개)
참고 항목
제품
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!