How i fix the error "Matrix dimensions must agree?"

1 次查看(过去 30 天)
xi=randi([10,30],4,4)
A=xi(1,:)
B=xi(:,1)
C=A - B
Why i get matrix dimensions must agree error.

回答(2 个)

Chunru
Chunru 2021-7-23
Which version of matlab you are using?
xi=randi([10,30],4,4)
xi = 4×4
13 17 21 15 14 12 14 11 13 28 28 16 20 14 24 25
A=xi(1,:)
A = 1×4
13 17 21 15
B=xi(:,1)
B = 4×1
13 14 13 20
% arrays with implicit expansion for newer matlab
% both A and B are expanded into compatible size before operation
C = A - B
C = 4×4
0 4 8 2 -1 3 7 1 0 4 8 2 -7 -3 1 -5
  1 个评论
DGM
DGM 2021-7-23
编辑:DGM 2021-7-23
IIRC, the generalized implicit expansion is R2016b and later. Prior to that, you can use bsxfun()
xi=randi([10,30],4,4);
A = xi(1,:);
B = xi(:,1);
C1 = A - B % R2016b and later
C1 = 4×4
0 6 5 -1 -11 -5 -6 -12 -13 -7 -8 -14 -13 -7 -8 -14
C2 = bsxfun(@minus,A,B) % R2007a and later
C2 = 4×4
0 6 5 -1 -11 -5 -6 -12 -13 -7 -8 -14 -13 -7 -8 -14

请先登录,再进行评论。


Image Analyst
Image Analyst 2021-7-23
Not sure what you want or are expecting because you forgot to tell us. Perhaps you want a 1-dimensional, 4-element vector. If so, here is how to do it.
xi = randi([10, 30], 4, 4) % 4-by-4 matrix.
A = xi(1, :) % Row vector
B = xi(:, 1) % Column vector
C1 = A(:) - B(:) % C will be a column vector.
C2 = A - B' % C will be a column vector.
C1 =
0
-7
-16
2
C2 =
0 -7 -16 2
If you want a 2-D matrix, then C=A-B works with no error in recent versions of MATLAB that do implicit expansion. But you also forgot to list your release when you posted. Here is another chance to read the posting guidelines and edit your post to improve it:

类别

Help CenterFile Exchange 中查找有关 Logical 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by