How to define and plot a piecewise function using if/elseif
조회 수: 9 (최근 30일)
이전 댓글 표시
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
댓글 수: 0
채택된 답변
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
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
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 Center 및 File Exchange에서 Line Plots에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!