Some aspects of the array syntax are great, others are a bit puzzling
1 view (last 30 days)
Show older comments
Cynthia Moore
on 6 Apr 2020
Commented: Walter Roberson
on 6 Apr 2020
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 Comments
Accepted Answer
Walter Roberson
on 6 Apr 2020
Edited: Walter Roberson
on 6 Apr 2020
[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 Comments
Yair Altman
on 6 Apr 2020
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)
More Answers (0)
See Also
Categories
Find more on Matrix Indexing in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!