Error: Matrix Dimensions must agree, creating a plot
Ältere Kommentare anzeigen
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');
Antworten (1)
Walter Roberson
am 17 Sep. 2015
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 Kommentar
Muhammad Azrul Izmee
am 27 Jan. 2022
THIS IS NOT VALID.. ALL OF YOU GAVE THE SAME ANSWER BUT WHY IT KEEP GETTING ERROR?
Kategorien
Mehr zu 2-D and 3-D Plots finden Sie in Hilfe-Center und File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!