Skip to content Skip to sidebar Skip to footer

Python: Multiply Two 1d Matrices In Numpy

a = np.asarray([1,2,3]) b = np.asarray([2,3,4,5]) a.shape (3,) b.shape (4,) I want a 3 by 4 matrix that's the product of a and b 1 2 * 2 3 4 5 3 np.dot(a, b.transpose(

Solution 1:

This is np.outer(a, b):

In [2]: np.outer([1, 2, 3], [2, 3, 4, 5])
Out[2]: 
array([[ 2,  3,  4,  5],
       [ 4,  6,  8, 10],
       [ 6,  9, 12, 15]])

Solution 2:

No need to use the matrix subtype. Regular array can be expanded to 2d (and transposed if need).

In [2]: a=np.array([1,2,3]) 
In [3]: b=np.array([2,3,4,5])

In [4]: a[:,None]
Out[4]: 
array([[1],
       [2],
       [3]])

In [5]: a[:,None]*b   # outer product via broadcasting
Out[5]: 
array([[ 2,  3,  4,  5],
       [ 4,  6,  8, 10],
       [ 6,  9, 12, 15]])

Other ways of making that column array

In [6]: np.array([[1,2,3]]).T
Out[6]: 
array([[1],
       [2],
       [3]])

In [7]: np.array([[1],[2],[3]])
Out[7]: 
array([[1],
       [2],
       [3]])

In [9]: np.atleast_2d([1,2,3]).T
Out[9]: 
array([[1],
       [2],
       [3]])

Solution 3:

Instead of asarray, use asmatrix.

import numpy as np
a = np.asmatrix([1,2,3])
b = np.asmatrix([2,3,4,5])
a.shape #(1, 3)
b.shape #(1, 4)
np.dot(a.transpose(),b)

Results in:

matrix([[ 2,  3,  4,  5],
        [ 4,  6,  8, 10],
        [ 6,  9, 12, 15]])

Solution 4:

the following code does as demanded basically you did a mistake while reshaping the arrays , you should reshape them so as to ensure matrix multiplication property is satisfied.

    a = np.asarray([1,2,3])
    b = np.asarray([2,3,4,5])
    a.reshape(3,1)

Post a Comment for "Python: Multiply Two 1d Matrices In Numpy"