[SciPy-User] Sparse matrix multiply

Jaakko Luttinen jaakko.luttinen at aalto.fi
Thu Mar 22 06:18:56 EDT 2012


On 03/22/2012 12:03 PM, Christopher Mutel wrote:
> On Thu, Mar 22, 2012 at 10:34 AM, Jaakko Luttinen
> <jaakko.luttinen at aalto.fi> wrote:
>> Hi!
>>
>> Why do I get two different results for the code below?
>>
>> import numpy as np
>> import scipy.sparse as sp
>> A = sp.rand(20,20,density=0.1)
>> B = sp.rand(20,20,density=0.1)
>> np.multiply(A,B).sum()
>> # out: 21.058793740984925
>> A.multiply(B).sum()
>> # out: 0.76482546226069481
>>
>> Am I missing something?
>> I think numpy.multiply should either return the correct answer or an
>> error that it can't compute the correct answer.
> 
> np.multiply performs element-wise multiplication, while A.multiply is
> matrix multiplication. They are both "correct", but answer different
> questions.

Actually it seems that np.multiply computes matrix multiplication in
this case! Below, only A.multiply(B) computes element-wise multiplication.

import numpy as np
import scipy.sparse as sp
A = sp.rand(20,20,density=0.1)
B = sp.rand(20,20,density=0.1)
np.multiply(A,B).sum()
# out: 25.240683127057885
A.multiply(B).sum()
# out: 2.6382118196920503
A.dot(B).sum()
# out: 25.240683127057885
np.dot(A,B).sum()
# out: 25.240683127057885

-Jaakko



More information about the SciPy-User mailing list