matrix multiplication of arrays in python
13,179
Solution 1
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.
Solution 2
>>> 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]])
Related videos on Youtube
Author by
Maxong091
Updated on June 04, 2022Comments
-
Maxong091 almost 2 years
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.]]
-
eumiro about 13 years+1, didn't know
np.outer
- but it looks like exactly what you need.