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?
>Solution :
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 "extended" into the appropriate size for addition, see this blog post on an in-depth explanation. In our toy example a is broadcast to [0, 1; 0, 1] and b to [0, 0; 18, 18], resulting in what you see as answer when each element is added to its equivalent index in the other matrix.