Nugroho's blog.: Numpy Slice Expression

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, :)




No comments:

323f (5) amp (1) android (12) apple (7) arduino (18) art (1) assembler (21) astina (4) ATTiny (23) blackberry (4) camera (3) canon (2) cerita (2) computer (106) crazyness (11) debian (1) delphi (39) diary (286) flash (8) fortran (6) freebsd (6) google apps script (8) guitar (2) HTML5 (10) IFTTT (7) Instagram (7) internet (12) iOS (5) iPad (6) iPhone (5) java (1) javascript (1) keynote (2) LaTeX (6) lazarus (1) linux (29) lion (15) mac (28) macbook air (8) macbook pro (3) macOS (1) Math (3) mathematica (1) maverick (6) mazda (4) microcontroler (35) mountain lion (2) music (37) netbook (1) nugnux (6) os x (36) php (1) Physicist (29) Picture (3) programming (189) Python (109) S2 (13) software (7) Soliloquy (125) Ubuntu (5) unix (4) Video (8) wayang (3) yosemite (3)