% Hi I am really stuck and would very much appreciate help!
% I want to make a graph that looks like this:
% Here is my code:
x = linspace(-5,5,50);
if (x>-2 & x<0)
Y = x*1.5+3
elseif (x>0 & x<2)
Y = x*(-1.5) + 3
else
Y = 0
end
plot(x,Y)
% How can I plot this?

 채택된 답변

Star Strider
Star Strider 2018년 12월 15일

1 개 추천

This version uses ‘logical indexing’ in the function:
x = linspace(-5,5,50);
Yfcn = @(x) (x*1.5+3).*(x>-2 & x<0) + (x*(-1.5) + 3).*(x>0 & x<2);
figure
plot(x, Yfcn(x))
grid
It is essentially your code, otherwise.

댓글 수: 2

Agnes Lindsten
Agnes Lindsten 2018년 12월 15일
Ah, thank you so much!
Tried to do something similar before, but failed with the dots. xP
Star Strider
Star Strider 2018년 12월 15일
As always, my pleasure!
The expressions and the logical values are both vectors, so it is necessary to use element-wise operations (here, multiplication) with them. See the documentation section on Array vs Matrix Operations (link) for an extended discussion.

댓글을 달려면 로그인하십시오.

추가 답변 (0개)

카테고리

도움말 센터File Exchange에서 2-D and 3-D Plots에 대해 자세히 알아보기

제품

릴리스

R2018b

질문:

2018년 12월 15일

댓글:

2018년 12월 15일

Community Treasure Hunt

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

Start Hunting!

Translated by