필터 지우기
필터 지우기

Some aspects of the array syntax are great, others are a bit puzzling

조회 수: 3 (최근 30일)
I have been going through the inroductory material and trying out things as I go. I came across a couple of questions in the arrays section.
First, I tried
[2 4 6 8]*2
4 8 12 16
Great. Next I tried
[1 2 3;4 5 6]*2
2 4 6
8 10 12
Super. If I can multiply an array by a scalar, I wondered if I could multiply a 2 dimensional array by a vector, so I tried
[1 2 3;4 5 6]*[1 2 3]
That got an error indicating that I was confusing matrix multiplication and elementwise multiplication.
So I tried both
[1 2 3 4;2 3 4 5]*[1 2;3 4;5 6;7 8]
50 60
66 80
[1 2 3 4;2 3 4 5].*[1 2 3 4]
1 4 9 16
2 6 12 20
This is great,
Then, just to be a pest, I tried:
[1 2 [3 4] 5]
1 2 3 4 5
What the heck? It seems to me that this should either be an error or the 3rd element should, itself, be a vector.
Finally, I tried
[1 2 3; 4 5 6; 7 8 9'].+[1 2 3]
That got an error. How come I can do element-wise multiplication but not addition?
I have to say that I really like the Alt+Enter to toggle between test and code mode. :-)

채택된 답변

Walter Roberson
Walter Roberson 2020년 4월 6일
편집: Walter Roberson 2020년 4월 6일
[1 2 [3 4] 5]
is short for
horzcat(1, 2, [3 4], 5)
which in turn would be short for
horzcat(1, 2, horzcat(3, 4), 5)
and there is no problem doing concatenation between a vector and a vector giving a longer vector result.
Consider that you could also have tried
A = [3 4]
[1 2 A 5]
This is valid in MATLAB as long as the number of rows generated by the part to the left of the A in [1 2 A 5] is the same as the number of rows in A, and the number of rows after [1 2 A] is the same as the number of rows in [5]
MATLAB [A B] syntax does not mean to set individual elements with individual scalars A and B: it means to drop in the contents of A and B and concatenate them together on the second dimension (by default), or on the first dimension if you use ; as the delimiter like [1 2;3 4] is vertcat(horzcat(1,2), horzcat(3,4))
How come I can do element-wise multiplication but not addition?
Addition and subtraction and logical and (&) and logical or (|) and relationship operators < and > and == and <= and >= and ~= are always element-by-element already and do not need a special element-by-element form.
  댓글 수: 4
Yair Altman
Yair Altman 2020년 4월 6일
Actually, .\ is also fully ducumented, as the ldivide function https://www.mathworks.com/help/matlab/ref/ldivide.html (just as ./ is documented as the rdivide function)
Walter Roberson
Walter Roberson 2020년 4월 6일
So it is! I was sure that I had looked before and it wasn't there!

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

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Matrices and Arrays에 대해 자세히 알아보기

태그

Community Treasure Hunt

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

Start Hunting!

Translated by