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!
采纳的回答
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!