Error: Matrix Dimensions must agree, creating a plot

Hi, I am trying to create a plot of a function over a period of time. The error is in line 19 (where L is defined). It says matrix dimensions must agree, But I don't understand that.
The program is basically trying to compare a solution from ODE45 and an analytical solution.
This is my code:
m=5;
c=0.5;
k=10;
tau=1/2*(sqrt(c^2/(k*m)));
wn=sqrt(k/m);
wd=wn*(sqrt(1-tau^2));
z0=[1,0];
tspan=[0 30];
[t,y]=ode45('msd',tspan,z0);
subplot(2,1,1);
title('30 second');
plot(t,y(:,1));
q0=1;
v0=0;
p=linspace(0,30);
L=(exp(-(tau*wn*p))*((q0*cos(wd*p))+((tau*wn*q0/wd)+(v0/wd))*sin(wd*p)));
subplot(2,1,2);
plot(p,L);
title('analytical');

답변 (1개)

Walter Roberson
Walter Roberson 2015년 9월 17일
L = (exp(-(tau .* wn .* p)) .* ((q0 .* cos(wd .* p)) + ((tau .* wn .* q0 ./ wd) + (v0 ./ wd)) .* sin(wd .*p)));
In particular,
(exp(-(tau*wn*p))*((q0*cos(wd*p))
the exp() is going to result in a row vector because p is a row vector. The cos() is going to result in a row vector because p is a row vector. So you end up with a row vector "*" a row vector. But "*" is matrix multiplication, so you are trying to matrix-multiply a 1 x 100 array by a 1 x 100 array. In matrix multiplication, the width of the left operand must agree with the height of the right operand, "the inner dimensions" must agree. 100 does not agree with 1. So you have a problem. You could use p' * p so you were multiplying a 100 x 1 by 1 x 100 to get a 100 x 100 result, or you could use p * p' for 1 x 100 * 100 x 1 to get a 1 x 1 result. But to get a 1 x 100 result you need to use the element-by-element multiplication operator named .*

댓글 수: 1

THIS IS NOT VALID.. ALL OF YOU GAVE THE SAME ANSWER BUT WHY IT KEEP GETTING ERROR?

댓글을 달려면 로그인하십시오.

카테고리

도움말 센터File Exchange에서 2-D and 3-D Plots에 대해 자세히 알아보기

질문:

2015년 9월 17일

댓글:

2022년 1월 27일

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by