sabato 23 gennaio 2010

IDL2PYTHON dictionary: how to save and load arrays

One of the most useful function in IDL is the save/restore function.
In Python it is very easy to store and reload data too.
Let's say we have an array A(50,50) and we want to save/load it in/from the directory "/home/user/":


from scipy import *

save('/home/user/A', A)
load('/home/user/A.npy')


giovedì 21 gennaio 2010

IDL2PYTHON dictionary: where function 1/2

The IDL where function is a very useful tool. In this post a will briefly report how to obtain the same with Python.
We define a float matrix 5x5, we will assign two non zero values at two of its components.
Then we discover how to obtain the coordinates (i,j) of the non zero values.
This can be done easily in one line of code.

Library needed: scipy


from scipy import * #this imports all the scipy functions

a=zeros([5,5], float) #an example of matrix
a[1,2]=4
a[4,3]=5
(i,j)=(a>3).nonzero()
# where a is greater than 3:

so i and j are the indices of the matrix where a satisfies the condition above:
>>> print i[0]
1
>>> print i[1]
4
>>> print j[0]
2
>>> print j[1]
3



For those who know IDL it is easy to see how this Python command is much more flexible then IDL where() function.