Take the 2-minute tour ×

The code below is giving me the correct answer, but only works when the arrays (plan and meas) are relatively small. When I try to run this over the arrays I actually need to compare (300x300 each), it takes forever (I don't know how long because I have been terminating it after 45 minutes.) I would like to only iterate over a range of array values around the index being evaluated (p). I tried to find documentation on the nditer flag 'ranged' but cannot find how to implement a specific range to iterate through.

p = np.nditer(plan, flags = ['multi_index','common_dtype'])
while not p.finished:
    gam_store = 100.0
    m = np.nditer(meas, flags = ['multi_index','common_dtype'])
    while not m.finished:
        dis_eval = np.sqrt(np.absolute(p.multi_index[0]-m.multi_index[0])**2 + np.absolute(p.multi_index[1]-m.multi_index[1])**2)           
        if dis_eval <= 6.0:
            a = (np.absolute(p[0] - m[0]) / maxdose) **2
            b = (dis_eval / gam_dist) **2
            gam_eval = np.sqrt(a + b)
            if gam_eval < gam_store:
                gam_store = gam_eval
    gamma = np.insert(gamma, location, gam_store, 0)
    location = location + 1
share|improve this question
Are you using np.insert to add values to the end of the array? If so, you should use np.append. It will be more optimized than np.insert. That may help a bit. –  SethMMorton May 14 '13 at 19:51
Maybe I'm misunderstanding the question. If you only want to iterate through a part of the array, why don't you just slice it? If not, what do you want to do with 'ranged'? –  askewchan May 14 '13 at 20:10
Slicing is a good idea. I was over thinking the problem. I will work on that. –  blake May 14 '13 at 20:16
@blake, I would try to slice before creating the nditer, e.g.: p = np.nditer(plan[a:b], ...) Also, if you want to get someone's attention, include their username: @blake. –  askewchan May 14 '13 at 21:10
@askwechan If I have a 2D numpy array, how do I slice an 2d area for example a 10x10 array around an index value? –  blake May 14 '13 at 22:23
add comment

1 Answer

up vote 2 down vote accepted

If you only want to iterate through a small part of the array, I think (unless I am misunderstanding the question) that you should just create an nditer instance from a slice of the array.

Say you only want the array near (i,j), then start with this:

w = 5    # half-size of the window around i, j
p = np.nditer(plan[i-w:i+w, j-w:j+w], flags=...)

This works because, say

a = array([[ 0,  1,  2,  3,  4],
           [ 5,  6,  7,  8,  9],
           [10, 11, 12, 13, 14],
           [15, 16, 17, 18, 19],
           [20, 21, 22, 23, 24]])


w = 1
i, j = 2,2
print a[i-w:i+w+1, j-w:j+w+1]
#array([[ 6,  7,  8],
#       [11, 12, 13],
#       [16, 17, 18]])
share|improve this answer
Thanks, that helped a lot. –  blake May 18 '13 at 19:27
add comment

Your Answer


