I recently stumbled upon the following behavior in MATLAB R2022a:
>> a = sparse(1,2,1)
a =
(1,2) 1
>> b = sparse(2,1,18)
b =
(2,1) 18
>> a+b
ans =
(2,1) 18
(1,2) 1
(2,2) 19
The presence of the (2,2) element with value 19 is quite puzzling. Intuitively, I would have expected to get either a zero (no element) or an error indicating that the vectors' sizes are not compatible. I couldn't find an explanation for this behavior in the documentation.
So, is this a bug or a feature?
This is due to implicit broadcasting and expected behaviour, also for full()
arrays. Compare:
bsxfun(@plus, [0 1], [0; 18])
ans =
0 1
18 19
(I'm running R2007b, so need bsxfun()
instead of implicit broadcasting).
What happens with unequal-sized vectors is that they are broadcast ("extended") into the appropriate size for addition, see e.g. this blog post on an in-depth explanation.
Verbosely writing our toy example
a = [0 1]
b = [ 0
18]
a + b = [0 1] + [ 0
18]
% Is broadcast to
= [0 1 [ 0 0
0 1] + 18 18]
% element wise addition
= [ 0 1
18 19]