Some aspects of the array syntax are great, others are a bit puzzling
1 次查看(过去 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. :-)
0 个评论
采纳的回答
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
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)
更多回答(0 个)
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Matrices and Arrays 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!