Mathematics Stack Exchange is a question and answer site for people studying math at any level and professionals in related fields. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

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.

share|cite|improve this question

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;

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).

share|cite|improve this answer
function y=f(t)
    y1=(-3*t).*(-pi<=t & t<=0);
    y2=(3*t).*(0<t & t<pi);


From matlab workspace call function and plot by the following

share|cite|improve this answer

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.