Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Sum of sparse vectors: bug or feature?

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading