Johnny
Johnny

Reputation: 869

I am having trouble multiplying two matrices with numpy

I am trying to use numpy to multiply two matrices:

import numpy as np

A = np.array([[1, 3, 2], [4, 0, 1]])
B = np.array([[1, 0, 5], [3, 1, 2]])

I tested the process and ran the calculations manually, utilizing the formula for matrix multiplications. So, in this case, I would first multiply [1, 0, 5] x A, which resulted in [11, 9] and then multiply [3, 1, 2] x B, which resulted in [10, 14]. Finally, the product of this multiplication is [[11, 9], [10, 14]]

nevertheless, when I use numpy to multiply these matrices, I am getting an error:

ValueError: shapes (2,3) and (2,3) not aligned: 3 (dim 1) != 2 (dim 0)

Is there a way to do this with python, successfully?

Upvotes: 0

Views: 61

Answers (1)

zglin
zglin

Reputation: 2919

Read the docs on matrix multiplication in numpy, specifically on behaviours.

The behavior depends on the arguments in the following way.

If both arguments are 2-D they are multiplied like conventional matrices. If either argument is N-D, N > 2, it is treated as a stack of matrices residing in the last two indexes and broadcast accordingly. If the first argument is 1-D, it is promoted to a matrix by prepending a 1 to its dimensions. After matrix multiplication the prepended 1 is removed. If the second argument is 1-D, it is promoted to a matrix by appending a 1 to its dimensions. After matrix multiplication the appended 1 is removed.

to get your output, try transposing one before multiplying?

c=np.matmul(A,B.transpose())

array([[11, 10],
       [ 9, 14]])

Upvotes: 1

Related Questions