# Piecewise function plot in Matlab

Is it possible in Matlab to plot an even piecewise function like:

$f(x) = \begin{cases} 3t , 0 < t < \pi \\ -3t , -\pi \le t \le 0 \end{cases}$

which has a period of $2\pi$.

I can't seem to find out how to plot a piecewise function properly. I can get it by plotting two separate graphs and by using the hold on capability.

-

You can always concatenate the data from your two functions before plotting. However, here's a solution similar to that of @user1772257 that uses logical indexing to avoid extra multiplication, addition, and also sets values outside of both ranges to NaN:

function y = f(t)
t1 = (t>0 & t<pi);    % (0, pi)
t2 = (t>=-pi & t<=0); % [-pi, 0]
y = NaN(size(t));     % Pre-allocate and set for [-Inf, -pi), [pi, Inf]
y(t1) = 3*t(t1);
y(t2) = -3*t(t2);


Note that this scheme is careful to evaluate each piece only at values for which it is valid. This can be useful if more complex functions are computationally expensive or generate errors or extrema at out-of-range values. If you want it periodic, then you'll need to add mod in various places. However, if you know that your input will always be $[-\pi, \pi)$, or don't care, then the following optimization can be used

function y = f(t)
t1 = (t>0 & t<pi);
y(t1) = 3*t(t1);
t1 = ~t1;
y(t1) = -3*t(t1);


Then plot with

t = -pi:0.01:pi;
plot(t,f(t))


You also could consider adding the line y = zeros(size(t)); in the second function before the pieces are evaluated to avoid occasional memory reallocation in some cases (probably not costly in current Matlab version unless the function has many pieces and/or is called many times).

-
function y=f(t)
y1=(-3*t).*(-pi<=t & t<=0);
y2=(3*t).*(0<t & t<pi);
y=y1+y2;

end


From matlab workspace call function and plot by the following

 x=-pi:.01:pi;
y=f(x);
plot(x,y);

-