4

I want to add every columns of a matrix to a numpy array, but numpy.broadcast only allows to add every rows of a matrix to an array. How can I do this?

My idea is to first transpose the matrix then add it to the array then transpose back, but this uses two transposes. Is there a function to do it directly?

tian tong
  • 793
  • 3
  • 10
  • 21

1 Answers1

3

Instead of using an array you could use a second matrix with just one column:

matrix = np.matrix(np.zeros((3,3)))
array = np.matrix([[1],[2],[3]])
matrix([[1],
        [2],
        [3]])
matrix + array
matrix([[ 1.,  1.,  1.],
        [ 2.,  2.,  2.],
        [ 3.,  3.,  3.]])

If you originally have an array you can reshape it like this:

a = np.asarray([1,2,3])
matrix + np.reshape(a, (3,1))
matrix([[ 1.,  1.,  1.],
        [ 2.,  2.,  2.],
        [ 3.,  3.,  3.]])
Álvaro Marco
  • 2,029
  • 17
  • 29