[Tutor] How to use Numeric.zeros() / Resizing an array

Danny Yoo dyoo@hkn.eecs.berkeley.edu
Wed Oct 30 13:11:02 2002


On Wed, 30 Oct 2002, Alex Gillis wrote:

> I'll ask how to use the zeros function in Numeric, I import it fine but
> it won't recognise the parameters.  I want to create an empty array of
> variable length with content integers.

Hi Alex,

Can you show us what you tried?  We may be able to help you interpret the
error messages so that they make more sense.



The shape of Numeric arrays is fixed at construction time:

###
>>> import Numeric
>>>
>>> Numeric.zeros
<built-in function zeros>
>>>
>>> Numeric.zeros.__doc__
"zeros((d1,...,dn),typecode='l',savespace=0) will return a new array of
shape (d1,...,dn) and type typecode with all it's entries initialized to
zero.  If savespace is nonzero the array will be a spacesaver array."
>>>
>>> Numeric.zeros([10,10])
array([[0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
       [0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
       [0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
       [0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
       [0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
       [0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
       [0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
       [0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
       [0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
       [0, 0, 0, 0, 0, 0, 0, 0, 0, 0]])
###



so unlike Python lists, Numeric arrays don't expand automatically.
Instead, an array can be resize()d:

    http://www.pfdubois.com/numpy/html2/numpy-6.html#pgfId-68290


###
>>> z = Numeric.zeros([5, 5])
>>> z
array([[0, 0, 0, 0, 0],
       [0, 0, 0, 0, 0],
       [0, 0, 0, 0, 0],
       [0, 0, 0, 0, 0],
       [0, 0, 0, 0, 0]])
>>> z2 = Numeric.resize(z, (3,3))
>>> z
array([[0, 0, 0, 0, 0],
       [0, 0, 0, 0, 0],
       [0, 0, 0, 0, 0],
       [0, 0, 0, 0, 0],
       [0, 0, 0, 0, 0]])
>>> z2
array([[0, 0, 0],
       [0, 0, 0],
       [0, 0, 0]])
###


Is this what you're looking for?



Good luck!