Ziyuan
Ziyuan

Reputation: 4558

Using broadcasting to multiply matrix rows according to elements in a vector?

Let's say I have a matrix

x=array([[ 0.,  0.,  0.],
       [ 0.,  0.,  1.],
       [ 0.,  1.,  0.],
       [ 0.,  1.,  1.],
       [ 1.,  0.,  0.],
       [ 1.,  0.,  1.],
       [ 1.,  1.,  0.],
       [ 1.,  1.,  1.]])

I want to get

array([[ 0.,  0.,  0.],
       [ 0.,  0.,  2.],
       [ 0.,  3.,  0.],
       [ 0.,  4.,  4.],
       [ 5.,  0.,  0.],
       [ 6.,  0.,  6.],
       [ 7.,  7.,  0.],
       [ 8.,  8.,  8.]])

How to write the one-line expression between x and range(1,9)? And what is the code for the same operation for columns?

Upvotes: 2

Views: 73

Answers (1)

Fred Foo
Fred Foo

Reputation: 363517

x * np.arange(1, 9).reshape(-1, 1)

or

x * arange(1, 9)[:, np.newaxis]

Both forms make a column vector out of arange(1, 9), which broadcasts nicely along the y axis of x.

"The same operation for columns" is just the transpose of the above, i.e. skip the reshape operation:

x * arange(1, 4)

Upvotes: 4

Related Questions