Potting graphs with if else and for
3 views (last 30 days)
Show older comments
Gayathri Thilakrathne
on 5 Nov 2020
Edited: Walter Roberson
on 7 Jan 2021
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 Comments
Accepted Answer
Sindar
on 5 Nov 2020
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)
More Answers (0)
See Also
Categories
Find more on Annotations 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!