Eli Borodach
Eli Borodach

Reputation: 597

How to multiply rows in matrices in Python?

My question is very intuitive in arrays but not in matrices. How can I multiple one element from row of one matrix in all equivalent row in other matrix. Let's assume I have:

x = np.matrix([[1], [2]])
y = np.matrix([[3, 4], [5, 6]])

and I want to get as a result:

[[3, 4], [10, 12]

or in a more readable way:

x = 1
    2

y = 3 4

    5 6

and I want to get as a result:

3 4

10 12

Upvotes: 3

Views: 6622

Answers (1)

MaxU - stand with Ukraine
MaxU - stand with Ukraine

Reputation: 210832

UPDATE: you can use np.multiply() function:

In [57]: x
Out[57]:
matrix([[1],
        [2]])

In [58]: y
Out[58]:
matrix([[3, 4],
        [5, 6]])

In [59]: np.multiply(y, x)
Out[59]:
matrix([[ 3,  4],
        [10, 12]])

OLD answer:

it would work out of the box if you would use np.array instead of np.matrix:

In [44]: xx = np.array([[1], [2]])

In [45]: yy = np.array([[3, 4], [5, 6]])

In [46]: xx
Out[46]:
array([[1],
       [2]])

In [47]: yy
Out[47]:
array([[3, 4],
       [5, 6]])

In [48]: yy * xx
Out[48]:
array([[ 3,  4],
       [10, 12]])

This answer might help to understand the difference between np.array and np.matrix

Upvotes: 3

Related Questions