Why is nothing coming up on my plot?
Show older comments
for x = -5:0.01:5
if x <= -1
y = 20;
elseif x > -1 && x <= 1
y = -5 * x + 10;
elseif x > 1 && x <= 3
y = -10 * x^2 + 35 * x - 20;
elseif x > 3 && x >= 4
y = -5 * x +10;
else
y = -10;
end
plot(x,y)
axis([-5,5,-100,100])
xlabel('x')
ylabel('y')
end
Answers (3)
MATLAB is a high-level language, so forget about loops and use logical indexing:
x = -5:0.01:5;
y = -10+zeros(1,numel(x));
y(x<=-1) = 20;
idx = (x>-1 & x<=1) | (x>3 & x<=4);
y(idx) = -5*x(idx) + 10;
idx = (x>1 & x<=3);
y(idx) = -10*x(idx).^2 + 35*x(idx)-20;
And lets have a look at it:
>> plot(x,y,'-o')

madhan ravi
on 8 Nov 2018
Edited: madhan ravi
on 8 Nov 2018
no need of loop
x = -5:0.01:5;
y =ones(1,numel(x)).*(-10);
y(x<=-1)=20;
y((x > -1 & x <= 1) | (x > 3 & x <= 4))=-5 .* x((x > -1 & x <= 1) | (x > 3 & x <= 4))+ 10;
y(x > 1 & x <= 3) = -10 .* x(x > 1 & x <= 3).^2 + 35 .* x(x > 1 & x <= 3) - 20;
plot(x,y)
axis([-5,5,-100,100])
xlabel('x')
ylabel('y')
your corrected loop way:
x = -5:0.01:5
for i = 1:numel(x)
if x(i) <= -1
y(i) = 20; %note here (i) is put in order to avoid overwriting
elseif x(i) > -1 & x(i) <= 1
y(i) = -5 * x(i) + 10;
elseif x(i) > 1 & x(i) <= 3
y(i) = -10 .* x(i).^2 + 35 .* x(i) - 20;
elseif x(i) > 3 & x(i) <= 4
y(i) = -5 * x(i) +10;
else
y(i) = -10;
end
end
plot(x,y)
axis([-5,5,-100,100])
xlabel('x')
ylabel('y')
1 Comment
madhan ravi
on 8 Nov 2018
if this is what you are looking for accept the answer so that people know the question is solved else let know whats additionally required , I can see that you haven't responded to the previous(question) answerer
SEUNG RHI CHOI
on 8 Nov 2018
You didn't save y values.
i=1;
for x = -5:0.01:5
if x <= -1
y(i) = 20;
elseif x > -1 && x <= 1
y(i) = -5 * x + 10;
elseif x > 1 && x <= 3
y(i) = -10 * x^2 + 35 * x - 20;
elseif x > 3 && x >= 4
y(i) = -5 * x +10;
else
y(i) = -10;
end
i = i+1;
end
plot(-5:0.01:5,y);
axis([-5,5,-100,100])
xlabel('x');
ylabel('y');
Categories
Find more on Matrix Indexing 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!