1

Given python code with numpy:

import numpy as np
a = np.arange(6).reshape(3, 2)   # a = [[0, 1], [2, 3], [4, 5]]; a.shape = (3, 2)
b = np.arange(3) + 1             # b = [1, 2, 3]               ; b.shape = (3,)

How can I multiply each value in b with each corresponding row ('vector') in a? So here, I want the result as:

result = [[0, 1], [4, 6], [12, 15]]    # result.shape = (3, 2)

I can do this with a loop, but I am wondering about a vectorized approach. I found an Octave solution here. Apart from this, I didn't find anything else. Any pointers for this? Thank you in advance.

Payas Krishna
  • 113
  • 1
  • 1
  • 7

2 Answers2

2

Probably the simplest is to do the following.

import numpy as np
a = np.arange(6).reshape(3, 2)   # a = [[0, 1], [2, 3], [4, 5]]; a.shape = (3, 2)
b = np.arange(3) + 1  

ans = np.diag(b)@a

Here's a method that exploits numpy multiplication broadcasting:

ans = (b*a.T).T

These two solutions basically take the same approach

ans = np.tile(b,(2,1)).T*a
ans = np.vstack([b for _ in range(a.shape[1])]).T*a
Ben Grossmann
  • 4,387
  • 1
  • 12
  • 16
  • 1
    No need to use the transposes to take advantage of broadcasting: `a*b[:,None]`. `b.T` does nothing since `b` is 1d. – hpaulj Apr 08 '22 at 19:50
  • I got rid of the redundant transpose. I didn't know about the none indexing trick! That's nice – Ben Grossmann Apr 08 '22 at 19:56
1
In [123]: a = np.arange(6).reshape(3, 2)   # a = [[0, 1], [2, 3], [4, 5]]; a.
     ...: shape = (3, 2)
     ...: b = np.arange(3) + 1             # b = [1, 2, 3]               ; b.
     ...: shape = (3,)
In [124]: a
Out[124]: 
array([[0, 1],
       [2, 3],
       [4, 5]])

A (3,1) will multiply a (3,2) via broadcasting:

In [125]: a*b[:,None]
Out[125]: 
array([[ 0,  1],
       [ 4,  6],
       [12, 15]])
hpaulj
  • 221,503
  • 14
  • 230
  • 353
  • Thank you for your answer! However, can you perhaps provide any explanation link for that None trick in broadcasting? I'm reading about it here - https://numpy.org/doc/stable/user/basics.broadcasting.html but this is very generic – Payas Krishna Apr 09 '22 at 07:36
  • 1
    It's the same as `np.newaxis` - there's an example on your link page. – hpaulj Apr 09 '22 at 14:07
  • 1
    @PayasKrishna Regarding the None trick for reshaping arrays, see [this page](https://numpy.org/doc/stable/user/basics.indexing.html#basics-indexing) under "Dimensional indexing tools" or [this SO post](https://stackoverflow.com/a/40575214/2476977). In short, hpaulj is reshaping `b` into a column vector so that multiplication broadcasting has the desired effect. – Ben Grossmann Apr 09 '22 at 14:17