3

How to multiply each column vector with a scalar from an array?

Example

a b c                        x1a x2b x3c
a b c     x1 x2 x3      ->   x1a x2b x3c
a b c                        x1a x2b x3c
a b c                        x1a x2b x3c

How to multiply each row vector with a scalar from an array?

Example

a a a a                        x1a x1a x1a x1a
b b b b     x1 x2 x3      ->   x2b x2b x2b x2b
c c c c                        x3c x3c x3c x3c

Recommendations for a better topic will be appreciated

2 Answers 2

4

I prefer the following syntax, which is short, but explicit

A = np.ones((3,4))
B = np.arange(3)
print A * B[:,None]

>>> array([[ 0.,  0.,  0.,  0.],
       [ 1.,  1.,  1.,  1.],
       [ 2.,  2.,  2.,  2.]])

A = np.ones((4,3))
B = np.arange(3)
print A * B[None,:]
>>> array([[ 0.,  1.,  2.],
       [ 0.,  1.,  2.],
       [ 0.,  1.,  2.],
       [ 0.,  1.,  2.]])
Sign up to request clarification or add additional context in comments.

Comments

2

1. Column multiplication

In [39]: A = array([[1,2,3],[1,2,3],[1,2,3],[1,2,3]])

In [40]: X = array([10,20,30])

In [41]: A
Out[41]: 
array([[1, 2, 3],
       [1, 2, 3],
       [1, 2, 3],
       [1, 2, 3]])

In [42]: X
Out[42]: array([10, 20, 30])

In [43]: A * X
Out[43]: 
array([[10, 40, 90],
       [10, 40, 90],
       [10, 40, 90],
       [10, 40, 90]])

1. Row multiplication

In [44]: B = array([[1,1,1,1],[2,2,2,2],[3,3,3,3]])

In [45]: B
Out[45]: 
array([[1, 1, 1, 1],
       [2, 2, 2, 2],
       [3, 3, 3, 3]])

In [46]: X = array([10,20,30])

In [47]: X
Out[47]: array([10, 20, 30])

In [48]: (B.transpose() * X).transpose()
Out[48]: 
array([[10, 10, 10, 10],
       [40, 40, 40, 40],
       [90, 90, 90, 90]])

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.