How to define and plot a piecewise function using if/elseif

조회 수: 9 (최근 30일)
Iakovos Antonoglou
Iakovos Antonoglou 2018년 6월 18일
댓글: Walter Roberson 2018년 6월 18일
Hello, i am trying to define and plot a piecewise fucntion specifically using if/elseif. The function is
f(x)=1,sin(x)>=1/2 f(x)=-1,sin(x)<=-1/2 f(x)=0,elsewise
I've trying using syms or function but i seem to be ending up with a problem, most commonly being any function i try to define inside an if gives me an error "x function not defined"
My latest attempt that produces no error but still doesnt work is
function gga(x)
x=linspace(0,4*pi)
if sin(x)>=1/2
y=1
elseif sin(x)<=-1/2
y=-1
else y=0
end
plot(x,y)
end

채택된 답변

Walter Roberson
Walter Roberson 2018년 6월 18일
Symbolic form:
syms x
f(x) = piecewise(sin(x) >= 1/2, 1, sin(x) <= -1/2, -1, 0);
fplot(f, [0 4*pi])
Numeric form:
y = zeros(size(x));
sx = sin(x);
mask = sx <= -1/2;
y(mask) = -1;
mask = sx >= 1/2;
y(mask) = 1;
It is also possible to construct it as a single numeric expression, but that takes a bit of thinking.
  댓글 수: 2
Iakovos Antonoglou
Iakovos Antonoglou 2018년 6월 18일
Hello, I am looking to use if/else if specifically,not the piecewise command. Thank you for your time
Walter Roberson
Walter Roberson 2018년 6월 18일
In order to do this using if/elseif/else you will need to loop over the elements.
for idx = 1 : length(x)
if sin(x(idx)) ...

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

추가 답변 (1개)

Ankita Bansal
Ankita Bansal 2018년 6월 18일
편집: Ankita Bansal 2018년 6월 18일
Hi Iakovos, the solution given by Walter can be rewritten as
x=linspace(0,4*pi);
y = zeros(size(x));
y(sin(x) <= -1/2) = -1;
y(sin(x) >= 1/2) = 1;
plot(x,y)
However, if you want to use if/else in your code then you can do this as
function gga
x=linspace(0,4*pi);
l=numel(x);
for i=1:l
if sin(x(i))>=1/2
y(i)=1;
elseif sin(x(i))<=-1/2
y(i)=-1;
else y(i)=0;
end
end
plot(x,y)
end

카테고리

Help CenterFile Exchange에서 Line Plots에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by