[Numpy-discussion] minor improvment to ones
Robert Kern
robert.kern@gmail....
Fri Jan 30 14:35:59 CST 2009
On Fri, Jan 30, 2009 at 08:22, Neal Becker <ndbecker2@gmail.com> wrote:
> Right now there are 2 options to create an array of constant value:
>
> 1) empty (size); fill (val)
>
> 2) ones (size) * val
>
> 1 has disadvantage of not being an expression, so can't be an arg to a
> function call.
So wrap it in a function.
> Also probably slower than create+fill @ same time
Only marginally. In any case, (1) is exactly how ones() and zeros()
are implemented. I would be +1 on a patch that adds a filled()
function along the lines of ones() and zeros(), but I'm -1 on adding
this functionality to ones() or zeros().
> 2 is probably slower than create+fill @ same time
>
> Now what would be _really_ cool is a special array type that would represent
> a constant array without wasting memory. boost::ublas, for example, has
> this feature.
In [2]: from numpy.lib.stride_tricks import as_strided
In [3]: def hollow_filled(shape, value, dtype=None):
...: x = asarray(value, dtype=dtype)
...: return as_strided(x, shape, [0]*len(shape))
...:
In [5]: hollow_filled([2,3,4], 5)
Out[5]:
array([[[5, 5, 5, 5],
[5, 5, 5, 5],
[5, 5, 5, 5]],
[[5, 5, 5, 5],
[5, 5, 5, 5],
[5, 5, 5, 5]]])
In [6]: hollow_filled([2,3,4], 5.0)
Out[6]:
array([[[ 5., 5., 5., 5.],
[ 5., 5., 5., 5.],
[ 5., 5., 5., 5.]],
[[ 5., 5., 5., 5.],
[ 5., 5., 5., 5.],
[ 5., 5., 5., 5.]]])
--
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 Numpy-discussion
mailing list