Potting graphs with if else and for
3 次查看(过去 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)
0 个评论
采纳的回答
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 Center 和 File Exchange 中查找有关 Annotations 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!