I am trying to plot a function and its derivatives with matlab. Getting the error “inner matrix dimensions must agree”

I want to plot x(t)=t*exp(-3*t)+0.25*exp(-3*t), and its first and second time derivatives.

I cannot even get the first plot correct. This is what I have done.

t = [0:0.01:3];
x = t*exp(-3*t)+0.25*exp(-3*t);
figure
plot(t,x);


From what I understand, that is saying that t goes from 0 to 3 in steps of 0.01 and x is the function I defined at that t. MatLab gives me this error

"Error using * Inner matrix dimensions must agree."

Can someone please let me know what's going on? I'm a matlab noob. I use mathematica quite a bit and I have used octave for making plots of data, but never to plot functions. I always do that stuff with mathematica!

-
If you have Mathematica, why not do this there? x[t_] := t Exp[-3 t] + 0.25 Exp[-3 t]. Plot[{x[t], x'[t], x''[t]}, {t, 3, 0.1}] – Amzoti Nov 3 '13 at 2:37
Why are you using Matlab at all? Plotting and taking derivatives of functions is much easier in Mathematica or Maple. – Stefan Smith Nov 3 '13 at 3:35
@Rich Williams : Also, pure Matlab questions with no math content are discouraged here. StackOverflow might be a better place to post. – Stefan Smith Nov 4 '13 at 0:26

you have to have

x = t.*exp(-3.*t)+0.25*exp(-3.*t)


this will do element by element multiplication

.* is the element by element multiplication for a vector, * is just multiplication.

-

Plotting and taking derivatives of functions in Matlab is perfectly easy. First you just need to use the symbolic math capabilities:

syms t;
x = t*exp(-3*t)+0.25*exp(-3*t);
xdot = diff(x,t,1)
xddot = diff(x,t,2)


Then to plot these you have several options. You can substitute in numeric values using subs, which automatically vectorizes your equations so you don't need to worry about adding .*:

t_ = 0:0.01:3;
x_ = subs(x,t,t_);
xdot_ = subs(xdot,t,t_);
xddot_ = subs(xddot,t,t_);
plot(t_,x_,'b',t_,xdot_,'g',t_,xddot_,'r')


Or you can use the ezplot function to directly plot the symbolic function over a range:

subplot(131);
ezplot(x,[0 3]);
subplot(132);
ezplot(xdot,[0 3]);
subplot(133);
ezplot(xddot,[0 3]);


The function fplot is another option if you convert your symbolic equations to numeric functions. This can be done manually or via the matlabFunction function:

subplot(131);
fplot(matlabFunction(x),[0 3])
subplot(132);
fplot(matlabFunction(xdot),[0 3])
subplot(133);
fplot(matlabFunction(xddot),[0 3])

-