-1

Is there a numpy operator that will result in the individual vector element multiplying with the corresponding matrix row?

For e.g.,

    import numpy
    a,b=numpy.array([1,2]), numpy.array([[1,2,3,4],[5,6,7,8]])

When I multiply a and b, I want the result to be

[[1,2,3,4],[10,12,14,16]]

where each vector element is multiplied with the corresponding matrix row elements.

I know how to implement this using loops, but I just wanted to know whether an in-built function exists in numpy for this, especially when b is an extremely large, but sparse matrix?

Thank you.

Your IDE
  • 111
  • 9

2 Answers2

1

You could use multiply like the following:

import numpy
a,b=numpy.array([1,2]), numpy.array([[1,2,3,4],[5,6,7,8]])
print(numpy.multiply(a,b.T).T)
# [[ 1  2  3  4]
# [10 12 14 16]]

Other option is to use * and transpose like the following:

import numpy
a,b=numpy.array([1,2]), numpy.array([[1,2,3,4],[5,6,7,8]])
print(a*b.T)
# [[ 1 10]
# [ 2 12]
# [ 3 14]
# [ 4 16]]
David
  • 8,113
  • 2
  • 17
  • 36
  • Thank you for the response, but can you expand the answer to include for large sparse matrices as well, like I asked in the question? – Your IDE May 10 '20 at 09:02
  • @YourIDE Please add a sample of the input and the desired output to the body of your question – David May 10 '20 at 09:32
  • I was referring to a similar method as in scipy.sparse, but I guess this will do since its just a vector with matrix multiplication. Also, in the 2nd method, it should be (a*b.T).T Thanks for the help. :) – Your IDE May 10 '20 at 09:43
1

You can use:

a[:,None]*b

This should be fairly fast with no extra calculation cost.

output:

[[ 1  2  3  4]
 [10 12 14 16]]
Ehsan
  • 12,072
  • 2
  • 20
  • 33
  • 1
    The `newaxis` option is also very elegant, I would add the following link to the reader https://stackoverflow.com/questions/37867354/in-numpy-what-does-selection-by-none-do – David May 10 '20 at 09:51