I am looking for a simple and efficient way to iterate on an matrix (2D array) by lines and columns. Using Python.
I have 3 2D-matrices of the same size: one containing x-coordinates, one for y-coordinates, and one containing the value for some data (temperature actually) at these coordinates.
I would like to iterate on every element of the 'data' matrix, but by keeping track of the current line and column, because I then need to look for the equivalent value in the 'x' and 'y' matrices.
To be clearer, I would write it like that in Matlab:
for i = 1:nb_line
for j = 1:nb_column
if data(i,j) ~= 0
<operations using x[i,j] and y[i,j]>
end
end
end
In Python, I was thinking in doing it like that:
for line in data:
for elt in line:
if not elt == 0:
<operations>
My problem is that I am loosing track of my current position in the array, and hence cannot call x[i,j] or y[i,j]...
What is the easiest way to do that? Thank you in advance.
EDIT: My code now looks as follows.
DATA
, LAT
and LON
are netCDF4.variables, which kinda look like 2-D masked arrays, respectively containing a geographical parameter (temperature, elevation, whatever...), its latitude and its longitude.
I want to project this data on a regular latitude/longitude grid (for example if the spatial step dlon
is 0.5 degree, the first column of my array correspond to longitude 0deg, the second longitude 0.5 deg, the third 1.0deg, etc...).
sizeLon = (lonMax-lonMin)/dlon
sizeLat = (latMax-latMin)/dlat
Mp = numpy.ma.masked_array(zeros((sizeLat,sizeLon)),mask=True)
for rows in zip(LST,LAT,LON):
for lstVal, latVal,lonVal in zip(*rows):
if lstVal is not numpy.ma.masked:
lp = round(-(latVal-latMin)/dlat)
cp = round((lonVal-lonMin)/dlon)
Mp[lp,cp] = lstVal