Numeric N-dimensional array initialization
Robert Kern
robert.kern at gmail.com
Thu Jun 22 14:34:50 EDT 2006
TG wrote:
> I tried to use Numeric.fromfunction, but there seems to be a problem :
>
> the function called must have the right number of args (hint : the
> number of dimensions, which I don't know). So i tried to use a function
> like :
>
> def myfunc(*args, **kw):
> return 0
>
> and then i get :
>
>>> Numeric.fromfunction(myfunc,(5,5))
> 0
>
> I'm a bit puzzled here
In [24]: def myfunc(*args):
....: print args
....:
....:
In [26]: fromfunction(myfunc, (2, 2))
(array([[0, 0],
[1, 1]]),
array([[0, 1],
[0, 1]]))
fromfunction() does not iterate over the possible indices and call the function
with scalar arguments to get a scalar return value. It generates N arrays with
index values in them and calls the function once with those arrays. The return
value should be another array.
If you actually just want 0s:
In [27]: zeros((5, 5))
Out[27]:
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]])
If you want 1s:
In [28]: ones((5, 5))
Out[28]:
array([[1, 1, 1, 1, 1],
[1, 1, 1, 1, 1],
[1, 1, 1, 1, 1],
[1, 1, 1, 1, 1],
[1, 1, 1, 1, 1]])
If you just want an array as fast as possible because you are going to fill in
values later:
In [29]: empty((5, 5))
Out[29]:
array([[ 13691, 0, 0, 2883587, 3],
[ 3, 0, 828189706, 6, 0],
[ 0, 9, 10, 828202281, 0],
[ 7, 0, 0, 0, 0],
[ 0, 0, 0, 0, 0]])
If you have more complicated needs, we can talk about them on numpy-discussion.
--
Robert Kern
"I have come to believe that the whole world is an enigma, a harmless enigma
that is made terrible by our own mad attempt to interpret it as though it had
an underlying truth."
-- Umberto Eco
More information about the Python-list
mailing list