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

If I want to make a piecewise function where lets say $f(x) = x^2 +1$ at $1 \leq t \leq 2$ and zero elsewhere. How can I make this possible using an anonymous function? I wanted to invent y = @(t) ((t.^2 + 1)*(t>=1)&&(t<=2))
But that obviously did not work out at all.


share|cite|improve this question
up vote 2 down vote accepted

The function you have works for scalar input, but I guess you want to make it for vectors, in that case you need to adjust it a bit:

y = @(t) ((t.^2 + 1).*(t>=1)&(t<=2))
share|cite|improve this answer
Thx! It worked for one. But when I tried this input it is all zeros. t2 = -0.5:0.01:1; x2 =@(t2) ((t2.^2-0.5).*((t2>=-0.5)&(t2<=1))); y_b =@(t2) -3.0*x2(t2-2); subplot(1,2,2) plot(t2,y_b(t2)) xlabel('t2') ylabel('y_b(t2)') axis([1.5 3 -2 1]) – user1945925 Jan 22 '13 at 13:40
@user1945925 Note that you evaluate x2(t2-2) which is all zero – Dennis Jaheruddin Jan 22 '13 at 13:48
Im not seeing it...when I write x2(t2-2) I want the graph to shift to the right by 2. Any recommendations? – user1945925 Jan 22 '13 at 13:50
You can just change the x values in the plot. – Dennis Jaheruddin Jan 22 '13 at 14:00
I thought I did by axis([1.5 3 -2 1]) – user1945925 Jan 22 '13 at 14:20

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.