How to define and plot a piecewise function using if/elseif
5 views (last 30 days)
Show older comments
Iakovos Antonoglou
on 18 Jun 2018
Commented: Walter Roberson
on 18 Jun 2018
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 Comments
Accepted Answer
Walter Roberson
on 18 Jun 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 Comments
Walter Roberson
on 18 Jun 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)) ...
More Answers (1)
Ankita Bansal
on 18 Jun 2018
Edited: Ankita Bansal
on 18 Jun 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
1 Comment
See Also
Categories
Find more on Line Plots in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!