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

5 visualizaciones (últimos 30 días)
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

Respuesta aceptada

Walter Roberson
Walter Roberson el 18 de Jun. de 2018
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 comentarios
Iakovos Antonoglou
Iakovos Antonoglou el 18 de Jun. de 2018
Hello, I am looking to use if/else if specifically,not the piecewise command. Thank you for your time
Walter Roberson
Walter Roberson el 18 de Jun. de 2018
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)) ...

Iniciar sesión para comentar.

Más respuestas (1)

Ankita Bansal
Ankita Bansal el 18 de Jun. de 2018
Editada: Ankita Bansal el 18 de Jun. de 2018
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

Categorías

Más información sobre Line Plots en Help Center y File Exchange.

Community Treasure Hunt

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

Start Hunting!

Translated by