[Numpy-discussion] Resizing without allocating additional memory

Travis Oliphant oliphant at ee.byu.edu
Wed Dec 6 12:45:03 CST 2006


David Huard wrote:

> Hi,
>
> I have fortran subroutines wrapped with f2py that take arrays as 
> arguments, and I often need to use resize(a, N) to pass an array of 
> copies of an element. The resize call , however, is becoming the speed 
> bottleneck, so my question is:
> Is it possible to create an (1xN) array from a scalar without 
> allocating additional memory for the array, ie just return a new 
> "view" of the array where all elements point to the same scalar.
>
I don't think this would be possible in Fortran because Fortran does not 
provide a facility for using arbitrary striding (maybe later versions of 
Fortran using pointers does, though). 

If you can use arbitrary striding in your code, then you can construct 
such a view using appropriate strides (i.e.  a stride of 0).  You can do 
this with the ndarray constructor:


a = array(5)
g = ndarray(shape=(1,10), dtype=int, buffer=a, strides=(0,0))

But, notice you will get interesting results using

g += 1

Explain why the result of this is an array of 15 (Hint:  look at the 
value of a).

-Travis



More information about the Numpy-discussion mailing list