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

$\begingroup$

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!

$\endgroup$ 3

2 Answers

$\begingroup$

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.

$\endgroup$ $\begingroup$

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])
$\endgroup$

Your Answer

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

You Might Also Like