How to cast an array column by column?

I want to add all matrix columns to a Numpy array, but numpy.broadcastallows me to add only all matrix rows to the array. How can i do this?

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

+4
source share
1 answer

Instead of using an array, you can use a second matrix with 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 initially have an array, you can change it as follows:

a = np.asarray([1,2,3])
matrix + np.reshape(a, (3,1))
matrix([[ 1.,  1.,  1.],
        [ 2.,  2.,  2.],
        [ 3.,  3.,  3.]])
+1
source

Source: https://habr.com/ru/post/1651262/


All Articles