user3190974
user3190974

Reputation: 11

how to multiply 2 matrices (Python)

Can anyone help me with this? I believe it's easy, but I don't know how to do it?

Create two matrices with elements 1,2,3,4,5 and 2,3,4,5,6 and matrix is multiply.

I have this, but I don't know how to multiply them:

import numpy as np
a=np.arange(5).reshape(1,5)
b=np.arange(6).reshape(1,6)
print a
print b

Thanks for help.

Upvotes: 0

Views: 2943

Answers (2)

jonrsharpe
jonrsharpe

Reputation: 122150

I think your problem is that your arrays aren't what you think they are:

>>> np.arange(5).reshape(1, 5)
array([[0, 1, 2, 3, 4]])
>>> np.arange(6).reshape(1, 6)
array([[0, 1, 2, 3, 4, 5]])

Instead, you probably want:

>>> np.arange(1, 6).reshape(1, 5)
array([[1, 2, 3, 4, 5]])
>>> np.arange(2, 7).reshape(1, 5)
array([[2, 3, 4, 5, 6]])

You can then multiply them directly:

>>> a = np.arange(1, 6).reshape(1, 5)
>>> b = np.arange(2, 7).reshape(1, 5)
>>> a*b
array([[ 2,  6, 12, 20, 30]])

Note that this is for element-wise multiplication. For the dot product, see leeladam's answer.

Upvotes: 3

leeladam
leeladam

Reputation: 1758

If you need mathematical matrix multiplication (dot product), use numpy.dot (see examples behind the link). Note that for numpy.dot, it DOES matter if the shape of your array is (5,1) or (1,5). You can transpose your array with a.T .

Upvotes: 3

Related Questions