Are the rules for element by element matrix operation changed?
Alessandro
on 13 Mar 2024
Latest activity Reply by Dyuman Joshi
on 16 Mar 2024
Hi
I have Matlab 2015b installed and if I try:
ones(2,3,4)+ones(2,3)
of course I get an error. But my student has R2023b installed and she gets a 2x3x4 matrix as a result, with all elements = 2.
How is it possible?
Thanks
A
10 Comments
Time DescendingWhy was this post transferred from Answers?
I'll just add that the introduction of singleton dimension expansion made me very happy. I'm still a bit pleased when I can replace bsxfun or repmat somewhere.
If it's a problem for students learning the language, then so will be broadcasting in Python and other languages. It's arguably better for students to learn early on of this convention.
Long ago, in a galaxy far, far away, we all used to use repmat to work with arrays of different sizes like that. Our code was good, and was blessed by the gods of MATLAB.
Then a good wizard named Loren helped us, providing us with the function bsxfun. It too was seen to be a good thing. But after some years of using bsxfun, the gods of MATLAB provided us with singleton dimension expansion. This happened with release R2016b. We all reveled in the beauty of our new tool, though even today some still lament the problems it creates. (Usually for new users, who are seen to be creating accidentally immense arrays.)
Now we can do things like this:
A = (0:4)' + (1:4)
which is a true boon for those of us who desire an addition table. ;-)
Seriously the ability to expand singleton dimensions when performing operations like that makes our code often much simpler and far more easy to read. The bsxfun and repmat solutions always felt like just something we needed to accept, but they never felt like something truly pretty in my eyes.
Yes, this behavior changed in R2016b.
Sign in to participate