Using mask() function to simulate if-then-else

Useful hints
Post Reply
User avatar
tomw
Posts: 296
Joined: Tue Dec 23, 2008 3:40 pm

Using mask() function to simulate if-then-else

Post by tomw »

Recently I was shown some great Jython code in someone's User Library that iterated through every data point for a time series of images, and computed this (several lines of code at the beginning and end are omitted here):

Code: Select all

....
....
for i in xrange(num_lines):
  for j in xrange(num_elements):
     k = j + i * num_elements;
     if (data1[k] < 230.):
       out[k] = (data1[k] - data2[k])
     else
       out[k] = -50.
....
....


This worked really well, but took several minutes to run. Instead of iterating through the values in Jython, I suggested a different function:

Code: Select all

def tops(source1, source2):
  m = mask(source1, "<", 230.)
  out = m * (source1 - source2 + 50.) - 50.
  return out


The mask() function clones the "source1" data field, and then replaces every value with either a 1.0 (for, in this case, values < 230) or a 0.0. The out= line then takes these 1s and 0s and uses them to either return the difference, or a value of -50.

Same result -- much faster to run....
Post Reply