2
votes

Let's say I do some calculation and I get a matrix of size 3 by 3 each time in a loop. Assume that each time, I want to save such matrix in a column of a bigger matrix, whose number of rows is equal to 9 (total number of elements in the smaller matrix). first I reshape the smaller matrix and then try to save it into one column of the big matrix. A simple code for only one column looks something like this:

import numpy as np
Big = np.zeros((9,3))
Small = np.random.rand(3,3)
Big[:,0]= np.reshape(Small,(9,1))
print Big

But python throws me the following error:

Big[:,0]= np.reshape(Small,(9,1)) ValueError: could not broadcast input array from shape (9,1) into shape (9)

I also tried to use flatten, but that didn't work either. Is there any way to create a shape(9) array from the small matrix or any other way to handle this error?

Your help is greatly appreciated!

1
You can just do Big[:,0]= np.reshape(Small,(9)) - C_Z_
Big[:,0] does slicing and therefore expects a 1D array, whereas np.reshape(Small,(9,1)) is a 2D. So, that's why as suggested by @C_Z_ you could reshape to 1D array like that or flatten to 1D with .ravel(). So, in summary, you could do : Big[:,0]= Small.ravel(). - Divakar
Thank you so much C_Z_ and Divakar. It worked! - Miranda

1 Answers

1
votes

try:

import numpy as np
Big = np.zeros((9,3))
Small = np.random.rand(3,3)
Big[:,0]= np.reshape(Small,(9,))
print Big

or:

import numpy as np
Big = np.zeros((9,3))
Small = np.random.rand(3,3)
Big[:,0]= Small.reshape((9,1))
print Big

or:

import numpy as np
Big = np.zeros((9,3))
Small = np.random.rand(3,3)
Big[:,[0]]= np.reshape(Small,(9,1))
print Big

Either case gets me:

[[ 0.81527817  0.          0.        ]
 [ 0.4018887   0.          0.        ]
 [ 0.55423212  0.          0.        ]
 [ 0.18543227  0.          0.        ]
 [ 0.3069444   0.          0.        ]
 [ 0.72315677  0.          0.        ]
 [ 0.81592963  0.          0.        ]
 [ 0.63026719  0.          0.        ]
 [ 0.22529578  0.          0.        ]]

Explanation

the shape of Big you are trying to assign to is (9, ) one-dimensional. The shape you are trying to assign with is (9, 1) two-dimensional. You need to reconcile this by making the two-dim a one-dim np.reshape(Small, (9,1)) into np.reshape(Small, (9,)). Or, make the one-dim into a two-dim Big[:, 0] into Big[:, [0]]. The exception is when I assigned 'Big[:, 0] = Small.reshape((9,1))`. In this case, numpy must be checking.