Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

matrix multiplication of arrays in python

I feel a bit silly asking this, but I can't seem to find the answer

Using arrays in Numpy I want to multiply a 3X1 array by 1X3 array and get a 3X3 array as a results, but because dot function always treats the first element as a column vector and the second as a row vector I can' seem to get it to work, I have to therefore use matrices.

A=array([1,2,3])  
print "Amat=",dot(A,A)  
print "A2mat=",dot(A.transpose(),A)  
print "A3mat=",dot(A,A.transpose())  
u2=mat([ux,uy,uz])  
print "u2mat=", u2.transpose()*u2  

And the outputs:

Amat= 14  
A2mat= 14  
A3mat= 14  
u2mat=  
 [[ 0.  0.  0.]  
        [ 0.  0.  0.]  
        [ 0.  0.  1.]]
like image 680
Maxong091 Avatar asked Dec 22 '22 15:12

Maxong091


2 Answers

np.outer is a builtin to do that:

A = array([1,2,3])
print( "outer:", np.outer( A, A ))

(transpose doesn't work because A.T is exactly the same as A for 1d arrays:

print( A.shape, A.T.shape, A[:,np.newaxis].shape )
>>> ( (3,), (3,), (3, 1) )

)

Added: np.add.outer adds pairs of elements -- np.outer is much like np.multiply.outer. And np.ufunc.outer (A, B) combines pairs with any binary ufunc.

like image 58
denis Avatar answered Jan 06 '23 06:01

denis


>>> A=np.array([1,2,3])
>>> A[:,np.newaxis]
array([[1],
       [2],
       [3]])
>>> A[np.newaxis,:]
array([[1, 2, 3]])
>>> np.dot(A[:,np.newaxis],A[np.newaxis,:])
array([[1, 2, 3],
       [2, 4, 6],
       [3, 6, 9]])
like image 30
Janne Karila Avatar answered Jan 06 '23 08:01

Janne Karila