5

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?

1 Answer 1

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.]])
Sign up to request clarification or add additional context in comments.

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.