Potting graphs with if else and for

1 次查看(过去 30 天)
Here i wanted to plot a graph wit these conditions. but it does not plot a graph. figure remains empty without a graph. how can i fix this
t = -4:0.1:4;
for k1 =1:length(t)
if (t(k1)>-4) && (t(k1)<-2)
x(k1) = (t(k1).^2) - (2.*t(k1))+3;
elseif (t(k1)>-2) && (t(k1)<2)
x(k1) = 4*cos(t(k1)*(2*pi*t(k1) - pi./8)) + 3*sin(2*pi*t(k1));
elseif (t(k1)>2) && (t(k1)<4)
x(k1) = sin(t(k1))./t(k1);
end
end
plot (t,x)

采纳的回答

Sindar
Sindar 2020-11-5
If it throws an error, please include that information.
If that error is what I'm seeing:
Error using plot. Vectors must be the same length.
then the issue is that you're conditions don't include an x-value when t=4 (or -2,2, but these will be filled in with zeros). You can use <=, >=, or you don't want those points plotted, insert NaNs:
t = -4:0.1:4;
for k1 =1:length(t)
if (t(k1)>-4) && (t(k1)<-2)
x(k1) = (t(k1).^2) - (2.*t(k1))+3;
elseif (t(k1)>-2) && (t(k1)<2)
x(k1) = 4*cos(t(k1)*(2*pi*t(k1) - pi./8)) + 3*sin(2*pi*t(k1));
elseif (t(k1)>2) && (t(k1)<4)
x(k1) = sin(t(k1))./t(k1);
else
x(k1) = nan;
end
end
plot(t,x)

更多回答(0 个)

类别

Help CenterFile Exchange 中查找有关 2-D and 3-D Plots 的更多信息

标签

Community Treasure Hunt

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

Start Hunting!

Translated by