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

1 view (last 30 days)
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)')

Accepted Answer

the cyclist
the cyclist on 20 Mar 2020
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)')

More Answers (1)

the cyclist
the cyclist on 20 Mar 2020
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)')

Categories

Find more on MATLAB in Help Center and File Exchange

Community Treasure Hunt

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

Start Hunting!