Monday, November 23, 2015

Numpy Slice Expression

 Suppossed we have two array a and b

 If we want to set b as finite difference result of a, we may tempted to do this

for i in range (9):
 b[i] = a[i+1]-a[i]

There's another (faster) way. The performance's close to the pure C, :)

b[:-1] = a[1:]-a[:-1]

What's that?

Numpy has slice form for array. If we have an array with length 10, the a[:] refers to all value in a.

a[1:] refers to a[1] to a[9] (without a[0])
a[3:] refers to a[3] to a[9]
a[:-1] refers to a[0] to a[8]
a[:-3] refers to a[0] to a[6]
a[1:-1] refers to a[1] to a[8]
...
and so on

Here's my tinkering with slice expression
>>> from numpy import *
>>> a = zeros(10)
>>> b = zeros(10)
>>> a[5]=1.
>>> a
array([ 0.,  0.,  0.,  0.,  0.,  1.,  0.,  0.,  0.,  0.])
>>> b
array([ 0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.])
>>> a[6]=2.
>>> a
array([ 0.,  0.,  0.,  0.,  0.,  1.,  2.,  0.,  0.,  0.])
>>> b[:-1]=a[:-1]-a[1:]
>>> b
array([ 0.,  0.,  0.,  0., -1., -1.,  2.,  0.,  0.,  0.])
>>> b[:-1]=a[:-1]+a[1:]
>>> b
array([ 0.,  0.,  0.,  0.,  1.,  3.,  2.,  0.,  0.,  0.])
>>> 

I like Python, :)