Info

This question is closed. Reopen it to edit or answer.

Matrix dimensions must agree.

1 view (last 30 days)
Fayez Alsunna
Fayez Alsunna on 17 Oct 2019
Closed: MATLAB Answer Bot on 20 Aug 2021
I have this code and I keep getiing this error "Matrix dimensions must agree.", please let me know how to fix it, thanks!!
I can not post the full code because its a project Im working on for class, but this line is where the issue is
ue = 1-2.*cos((3.*pi.*x)./(2.*L)).*exp(((9.*(pi.^2).*alpha)/(2.*L)).*-t)+4.*cos((15.*pi.*x)/(2.*L)).*exp(((9.*(pi.^2).*alpha)./(2.*L)).*-t);
x and t are defined as:
x = linspace(0,L,nx);
t = linspace(0,tmax,nt);
tmax, nt,nx, and L are just constant variables.
  1 Comment
Adam Danz
Adam Danz on 17 Oct 2019
Edited: Adam Danz on 17 Oct 2019
I see variables x,L,alpha,t (assuming pi is Matlab's built-in pi value).
We have no idea what those variables are nor their size (which is most important to this question).
The entire copy-pasted error message may also contain clues.
We're in the dark.
[update following the update in the question]
"x and t are defined as:
x = linspace(0,L,nx);
t = linspace(0,tmax,nt);
tmax, nt,nx, and L are just constant variables. "
That still doesn't tell us the size of those variables. You're dealing with a dimension mismatch error which means there's a conflict in the size of the variables. We can't solve that without knowing their sizes.
Star Strider is guessing in his answer that the error is due to a misuse of division and|or element-wise division which may be the case.
It appears that x and t are row-vectors and it looks like they could have different lengths. L is a scalar and I'm guessing alpha is a scalar too (???). That would result in an error here:
cos((3.*pi.*x)./(2.*L)) .* exp(((9.*(pi.^2).*alpha)/(2.*L)).*-t)
%[-------term 1--------] [--------------term 2-----------------]
Term 1 and term 2 will have different lengths.

Answers (1)

Star Strider
Star Strider on 17 Oct 2019
Edited: Star Strider on 17 Oct 2019
Note that you used element-wise division some times when you divided by ‘(2*L)’ but not other times:
ue = 1-2.*cos((3.*pi.*x)./(2.*L)).*exp(((9.*(pi.^2).*alpha)/(2.*L)).*-t)+4.*cos((15.*pi.*x)/(2.*L)).*exp(((9.*(pi.^2).*alpha)./(2.*L)).*-t);
See if doing it in every division no longer throws the error:
ue = 1-2.*cos((3.*pi.*x)./(2.*L)).*exp(((9.*(pi.^2).*alpha)./(2.*L)).*-t)+4.*cos((15.*pi.*x)./(2.*L)).*exp(((9.*(pi.^2).*alpha)./(2.*L)).*-t);
All other operations appear to be element-wise.
Note that you can do this automatically if you create your equation as a character array and then use the vectorize function on it. Remove the single quotes afterwards to use it in your calculations.
All the vectors in this assignment must have the same number of elements.

Tags

Community Treasure Hunt

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

Start Hunting!