Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 879
Ratbert Avatar asked Oct 27 '25 05:10

Ratbert


2 Answers

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]

like image 106
Adriaan Avatar answered Oct 28 '25 19:10

Adriaan


This is in fact similarly happening with full arrays, i.e. not restricted to sparse vectors, and this is normal behavior according to the documentation (see the Add Row and Column Vector section).

like image 44
Ratbert Avatar answered Oct 28 '25 20:10

Ratbert



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!