[SciPy-user] temporary copies for in-place array modification?

Alan G Isaac aisaac@american....
Tue Jul 29 00:31:16 CDT 2008


>> On Mon, 28 Jul 2008, Robert Kern apparently wrote:
>>> Unfortunately, a temporary is unavoidable. If you modify `a` in-place, 
>>> you will mess up the computation. For example, we could try using the 
>>> third argument to the subtract() ufunc to place the results back into 
>>> a[1:]:
>>> In [1]: import numpy 
>>> In [2]: a = numpy.arange(1,7)
>>> In [3]: numpy.subtract(a[1:], a[:-1], a[1:])
>>> Out[3]: array([1, 2, 2, 3, 3])

> 2008/7/28 Alan G Isaac <aisaac@american.edu>:
>> But he could work from the other end::
>>    >>> np.subtract(a[1:],a[:-1],a[:-1])
>>    array([1, 1, 1, 1, 1])
>> As long as he can then use a[:-1] instead of a[1:]. 
>> Right? 


Anne Archibald wrote:
> Maybe. The result is dependent on the memory layout of a. 


What would be the right test for this being ok?
And would you give an example where this will fail?
I assumed the implicit loop would always be over the
elements in the order they appear in the array.
E.g., ::

     >>> a = np.arange(20)
     >>> a2 = a[::-2]
     >>> a2.flags
       C_CONTIGUOUS : False
       F_CONTIGUOUS : False
       OWNDATA : False
       WRITEABLE : True
       ALIGNED : True
       UPDATEIFCOPY : False
     >>> np.subtract(a2[1:],a2[:-1],a2[:-1])
     array([-2, -2, -2, -2, -2, -2, -2, -2, -2])
     >>> a2
     array([-2, -2, -2, -2, -2, -2, -2, -2, -2,  1])

Thanks,
Alan




More information about the SciPy-user mailing list