# Matlab, anonymous functions, making a piecewise function, how?

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.

Thanks

-

## 1 Answer

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

-
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