what is wrong with my code, i am trying to plot below

2 次查看(过去 30 天)
for t = 1:.01:10;
if t <= pi
x = 1.41.*exp(-t).*sin(t+0.785);
elseif t > pi
x = 1.41.*exp(-t).*sin(t+0.785)-(exp(-(t-pi).*sin(t-pi)));
end
end
plot(t,x)
xlabel('t')
ylabel('X(t)')

采纳的回答

the cyclist
the cyclist 2020-3-20
In every iteration of the for loop, you are simply overwriting x, over and over.
Instead, you need to define a vector for x, too. Here is one way:
t = 1:.01:10;
tCount = numel(t);
x = zeros(tCount,1);
for nt = 1:tCount
if t(nt) <= pi
x(nt) = 1.41.*exp(-t(nt)).*sin(t(nt)+0.785);
elseif t(nt) > pi
x(nt) = 1.41.*exp(-t(nt)).*sin(t(nt)+0.785)-(exp(-(t(nt)-pi).*sin(t(nt)-pi)));
end
end
plot(t,x)
xlabel('t')
ylabel('X(t)')

更多回答(1 个)

the cyclist
the cyclist 2020-3-20
FYI, there is a much more efficient solution, which is to avoid the for loop altogether:
t = 1:.01:10;
x = zeros(size(t));
x(t<=pi) = 1.41.*exp(-t(t<=pi)).*sin(t(t<=pi)+0.785);
x(t>pi) = 1.41.*exp(-t(t>pi)).*sin(t(t>pi)+0.785)-(exp(-(t(t>pi)-pi).*sin(t(t>pi)-pi)));
plot(t,x)
xlabel('t')
ylabel('X(t)')

类别

Help CenterFile Exchange 中查找有关 MATLAB 的更多信息

标签

Community Treasure Hunt

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

Start Hunting!

Translated by