[Numpy-discussion] minor improvment to ones

Neal Becker ndbecker2 at gmail.com
Fri Jan 30 17:32:06 EST 2009


Robert Kern wrote:

> On Fri, Jan 30, 2009 at 08:22, Neal Becker <ndbecker2 at 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.]]])
>

Where can I find doc on stride_tricks?  Nothing here:
http://docs.scipy.org/doc/numpy/search.html?q=stride_tricks&check_keywords=yes&area=default






More information about the NumPy-Discussion mailing list