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

if statementpiece-wisepiecewise

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

Best Answer

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.