How to multiply 3X1 matrix with 1X3 matrix using numpy

Viewed 1454

I am trying to multiply [[3],[1],[0]] with matrix [1,-1,3] using numpy. But it is not able to perform that.

import numpy as np

a = np.array([[3],[1],[0]])
b = np.array([1,-1,3])

x = np.dot(a,b)
print(x)

it is returning error as " ValueError: shapes (3,1) and (3,) not aligned: 1 (dim 1) != 3 (dim 0) "

2 Answers

Actually your shape is not right (shape of b is (3,), it needs to be (1,3)) .

a = np.array([[3],[1],[0]])
b = np.array([[1,-1,3]])  #Make it 2D list to have shape (1, 3)
np.dot(a,b)

array([[ 3, -3,  9],
       [ 1, -1,  3],
       [ 0,  0,  0]])

You need to write b also as a matrix:

b = np.array([[1,-1,3]])
Related