How to plot Peicewise functions?

Hello there!
I am trying to script the following:
f(x)={x^2 0<=x<=1/2 && 1/2(1-x) for 1/2<x<1
and plot for 0<x<5
..................
Having tried :
function f = f_x(x)
if x<1/2
f=x^2
else if x<1
f=1/2(1-x)
else
f=0
end
this function to create the conditions how would I go to plot it?

1 Comment

Be sure to correct
f=1/2(1-x)
to
f=1/2*(1-x)
or
f=1/(2*(1-x))
as appropriate... your notation is ambiguous.

Sign in to comment.

Answers (2)

xvals = linspace(0, 5, 101); %plot at 101 points
y = zeros(size(xvals));
for K = 1 : length(xvals)
y(K) = f_x(xvals(K));
end
plot(xvals, y);

2 Comments

Thanks now any idea how to plot this periodic function from 0<x<5? so there will be 5 of these waveforms on the one graph.
The linspace(0, 5, 101) part says to choose values evenly spaced from 0 to 5 inclusive. If you want the 0 and 5 excluded, drop the first and last values of the array.
That function is not periodic. If you want it to be periodic, use
function f = f_x(X)
x = mod(X, 1);

Sign in to comment.

SANJU HAZRA
SANJU HAZRA on 16 Oct 2020
Edited: SANJU HAZRA on 16 Oct 2020
syms x
p = piecewise((0<=x<=0.5),x^2,(0.5<x<1),0.5*(x-1))
fplot(p,[0 5])

1 Comment

Note that piecewise() is one of the very few places in MATLAB where you can use range comparisons in that form LB <= x <= UB . In nearly all other contexts, LB <= x <= UB is interpreted as ((LB <= x) <= UB) where the first test returns a logical value and the logical value is compared to UB.
Another place that you can use LB <= x <= UB is in solve() .
The key is not exactly that the expression is symbolic: if you enter
0<=x<=0.5
at the command line then you will get back
(0 <= x) <= 1/2
Because this kind of range test works in so few places, I recommend against using it in code, as it could lead to people getting the wrong impression that such range tests are generally valid in MATLAB. It is not uncommon for people to write these kinds of range tests and to run into trouble because of it.

Sign in to comment.

Asked:

on 3 Dec 2013

Edited:

on 16 Oct 2020

Community Treasure Hunt

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

Start Hunting!