I have an arbitrary length vector, and I want to reshape it into a square matrix, something like:
np.arange(6).reshape((3, 3))
[1,2,x] [1,2,3]
[3,4,x] [4,5,6]
[5,6,x] [x,x,x]
The x
can be horizontally and/or vertically placed.
Obviously reshape
function will only allow parameter like (3,2) in the above example. Is there a way to produce effect of squared shaped matrix.Thanks.
The numpy. reshape() function allows us to reshape an array in Python. Reshaping basically means, changing the shape of an array. And the shape of an array is determined by the number of elements in each dimension.
If you have an array of shape (2,4) then reshaping it with (-1, 1), then the array will get reshaped in such a way that the resulting array has only 1 column and this is only possible by having 8 rows, hence, (8,1).
Python numpy. square() function returns a new array with the element value as the square of the source array elements. The source array remains unchanged.
You'll have to pad the array, either before or after reshape.
For example, using the resize
method to add the needed 0s:
In [409]: x=np.arange(6)
In [410]: x.resize(3*3)
In [411]: x.shape
Out[411]: (9,)
In [412]: x.reshape(3,3)
Out[412]:
array([[0, 1, 2],
[3, 4, 5],
[0, 0, 0]])
The np.resize
replicates values. np.pad
is also handy for adding 0s, though it might overkill.
With np.arange(6)
we can pad before or after reshape. With np.arange(5)
we have to stick with before, because the padding will be irregular.
In [409]: x=np.arange(6)
In [410]: x.resize(3*3)
In [411]: x.shape
Out[411]: (9,)
In [412]: x.reshape(3,3)
Out[412]:
array([[0, 1, 2],
[3, 4, 5],
[0, 0, 0]])
In any case there isn't one function that does all of this in one call - at least not that I know of. This isn't a common enough operation.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With