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

답변 (3개)

Stephen23
Stephen23 2018년 11월 8일
편집: Stephen23 2018년 11월 8일

1 개 추천

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
madhan ravi 2018년 11월 8일
편집: madhan ravi 2018년 11월 8일

0 개 추천

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

madhan ravi
madhan ravi 2018년 11월 8일
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
SEUNG RHI CHOI 2018년 11월 8일

0 개 추천

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');

카테고리

도움말 센터File Exchange에서 Matrix Indexing에 대해 자세히 알아보기

태그

질문:

2018년 11월 8일

댓글:

2018년 11월 8일

Community Treasure Hunt

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

Start Hunting!

Translated by