We wish to plot a piecewise function in matlab, and animate it. Since I have not figured out how to properly write piecewise functions in wordpress, I will split it up in three parts.

\displaystyle  f(x,t) = 0,\; x\leq 0,

\displaystyle  f(x,t) = x/t,\; 0<x<t

\displaystyle  f(x,t) = 1,\; x\geq t

We let {x=-1:0.01:2.0} and want to plot the function for different values of {t}.
First a quick example on how logical vectors in Matlab work.

EDU>> x = [1,3,4,5,6,7];
EDU>> x > 3

ans =

0  0  1  1  1  1

Say we wanted that some function has value {2} for all x’s larger than {3}. Then we can simply multiply our logical vector by {2}.

EDU>> 2.*(x>3)

ans =

0  0  2  2  2  2

By using this idea we can write the following code to plot and animate our function {f}:

x = -1:0.01:2.0

for t = 0:0.5:20
 y = (0).*(x<=0)+(x/t).*(0<x&x<t)+(1).*(x>=t);
 plot(x,y),hold on

About these ads