Python: Resize an existing array and fill with zeros
There is a new numpy function in version 1.7.0 numpy.pad
that can do this in one-line. Like the other answers, you can construct the diagonal matrix with np.diag
before the padding.The tuple ((0,N),(0,0))
used in this answer indicates the "side" of the matrix which to pad.
import numpy as npA = np.array([1, 2, 3])N = A.sizeB = np.pad(np.diag(A), ((0,N),(0,0)), mode='constant')
B
is now equal to:
[[1 0 0] [0 2 0] [0 0 3] [0 0 0] [0 0 0] [0 0 0]]
sigma.resize()
returns None
because it operates in-place. np.resize(sigma, shape)
, on the other hand, returns the result but instead of padding with zeros, it pads with repeats of the array.
Also, the shape()
function returns the shape of the input. If you just want to predefine a shape, just use a tuple.
import numpy as np...shape = (6, 6) #This will be some pre-determined sizesigma = np.diag(S) #diagonalise the matrix - this workssigma.resize(shape) #Resize the matrix and fill with zeros
However, this will first flatten out your original array, and then reconstruct it into the given shape, destroying the original ordering. If you just want to "pad" with zeros, instead of using resize()
you can just directly index into a generated zero-matrix.
# This assumes that you have a 2-dimensional arrayzeros = np.zeros(shape, dtype=np.int32)zeros[:sigma.shape[0], :sigma.shape[1]] = sigma