Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python: Resize an existing array and fill with zeros

I think that my issue should be really simple, yet I can not find any help on the Internet whatsoever. I am very new to Python, so it is possible that I am missing something very obvious.

I have an array, S, like this [x x x] (one-dimensional). I now create a diagonal matrix, sigma, with np.diag(S) - so far, so good. Now, I want to resize this new diagonal array so that I can multiply it by another array that I have.

import numpy as np ... shape = np.shape((6, 6)) #This will be some pre-determined size sigma = np.diag(S) #diagonalise the matrix - this works my_sigma = sigma.resize(shape) #Resize the matrix and fill with zeros - returns "None" - why? 

However, when I print the contents of my_sigma, I get "None". Can someone please point me in the right direction, because I can not imagine that this should be so complicated.

Thanks in advance for any help!

Casper

Graphical:

I have this:

[x x x] 

I want this:

[x 0 0] [0 x 0] [0 0 x] [0 0 0] [0 0 0] [0 0 0] - or some similar size, but the diagonal elements are important. 
like image 941
hjweide Avatar asked Feb 12 '12 18:02

hjweide


People also ask

How do you fill an empty array with zeros in Python?

empty() does not initialize the memory, therefore your array will be filled with garbage and you will have to initialize all cells. zeros() initializes everything to 0. Therefore, if your final result includes lots of zeros, this will save you the time to set all those array cells to zero manually.

How do you resize an array in Python?

With the help of Numpy numpy. resize(), we can resize the size of an array. Array can be of any shape but to resize it we just need the size i.e (2, 2), (2, 3) and many more. During resizing numpy append zeros if values at a particular place is missing.

How do you add zeros to an array in Python?

You can use numpy. pad , which pads default 0 to both ends of the array while in constant mode, specify the pad_width = (0, N) will pad N zeros to the right and nothing to the left: N = 4 np.

How do I make a NumPy array full of zeros?

The zeros() function is used to get a new array of given shape and type, filled with zeros. Shape of the new array, e.g., (2, 3) or 2. The desired data-type for the array, e.g., numpy. int8.


1 Answers

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 np  A = np.array([1, 2, 3])  N = A.size B = 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]] 
like image 110
Hooked Avatar answered Sep 20 '22 11:09

Hooked