A row vector and a column vector have compatible sizes. If you add a 1-by-3 vector to a 2-by-1 vector, then each vector implicitly expands into a 2-by-3 matrix before MATLAB executes the element-wise addition.
x = [1 2 3]
x =
1 2 3
y = [10; 15]
y =
10
15
x + y
ans =
11 12 13
16 17 18
If the sizes of the two operands are incompatible, then you get an error.
A = [8 1 6; 3 5 7; 4 9 2]
A =
8 1 6
3 5 7
4 9 2
m = [2 4]
m =
2 4
A - m
Matrix dimensions must agree.
This is from the MATLAB "Array vs. Matrix Operations page". Why does the second example output an error while the first doesn't? I see that the second example says that "matrix dimensions must agree", but why did that error not occur for the first example? A further explanation of this would be great. Thank you!

댓글 수: 1

Stephen23
Stephen23 2019년 10월 15일
Note that your title "Array vs. Matrix Operations" actually refers to different kinds of operators, not specifically to compatible array sizes for basic array operations:

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

 채택된 답변

Stephen23
Stephen23 2019년 10월 15일
편집: Stephen23 2019년 10월 15일

0 개 추천

What "compatible sizes" means is explained on this page:
I will not copy the entire page here, but the main points are:
  • scalar dimensions can be expanded/contracted to match the other array.
  • non-scalar dimensions must have exactly the same size.
That is all. So your first example works because (note the scalar dimensions):
  • 1x3 can be expanded to 2x3
  • 2x1 can be expanded to 2x3
But your second example fails because
  • 1x2 can be expanded to 3x2
  • 1x2 cannot be expanded/contracted to match 3x3,nor can 3x3 be expanded/contracted to match 1x2, because in the second dimension neither is scalar, nor do they have the same size.

추가 답변 (0개)

카테고리

도움말 센터File Exchange에서 Operators and Elementary Operations에 대해 자세히 알아보기

제품

질문:

2019년 10월 15일

편집:

2019년 10월 15일

Community Treasure Hunt

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

Start Hunting!

Translated by