Help with "Matrix Dimensions Must Agree"

I kept on getting an error saying "Matrix dimensions must agree. Error in LakeOntarioVolume (line 44) Y(i) = sum(c.*Z(i,:))*Dx/3;". The first loop works, but the second one doesn't even though I copied and pasted it. Any help would be appreciated, thank you.

1 Comment

Posting code as text is much more convenient for answering, because in opposite to a screenshot the code can be copied and pasted.

Sign in to comment.

 Accepted Answer

Jan
Jan on 28 Mar 2018
Edited: Jan on 29 Mar 2018
c is a 1x61 vector, and Z a 61x25 matrix. Then:
c .* Z(i, :)
tries to multiply a [1x61] and a [1x25] vector elementwise. This must fail. Maybe you mean:
c .* Z(:, i).'
No, this would not work with for i = 1:61. The problem might be at:
c = 2*ones(1, length(Z))
length replies the longest dimension. Try:
c = 2 * ones(1, size(Z, 2))
By the way: The loop is not needed:
Z = B.';
c = [1, 2 * ones(1, size(Z, 2)-2), 1];
c(2:2:end) = 4;
Y = sum(c .* Z, 2) * Dx / 3; % >= R2016b, array expansion
For older Matlab versions:
Y = sum(bsxfun(@times, c, Z), 2) * Dx / 3;

More Answers (1)

Adam Zhang
Adam Zhang on 29 Mar 2018
Thank you so much! The line c = [1, 2 * ones(1, size(Z, 2)-2), 1]; worked for me.

Categories

Asked:

on 28 Mar 2018

Answered:

on 29 Mar 2018

Community Treasure Hunt

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

Start Hunting!