0

I have a following function which finds distance between two trajectories, function recMethod() is the recursive function. I want to convert this recursive function to the iterative one.

def dist(pt1,pt2):
    return math.sqrt((pt2[0]-pt1[0])*(pt2[0]-pt1[0])+(pt2[1]-pt1[1])*(pt2[1]-pt1[1]))

def recMethod(ca,i,j,P,Q):
    if ca[i,j] > -1:
        return ca[i,j]
    elif i == 0 and j == 0:
        ca[i,j] = euc_dist(P[0],Q[0])
    elif i > 0 and j == 0:
        ca[i,j] = max(recMethod(ca,i-1,0,P,Q),euc_dist(P[i],Q[0]))
    elif i == 0 and j > 0:
        ca[i,j] = max(recMethod(ca,0,j-1,P,Q),euc_dist(P[0],Q[j]))
    elif i > 0 and j > 0:
        ca[i,j] = max(min(recMethod(ca,i-1,j,P,Q),recMethod(ca,i-1,j-1,P,Q),recMethod(ca,i,j-1,P,Q)),euc_dist(P[i],Q[j]))
    else:
        ca[i,j] = float("inf")
    return ca[i,j]
3

1 Answer 1

1

You just need to fill in the table ca in the right order, in this case from 0,0 to len(P)-1, len(Q)-1 One way to do it would be:

def iterative(ca, P,Q):
    ca[0,0] = euc_dist(P[0],Q[0])
    for ii in range(1,len(P)):
        ca[ii,0] = max(ca[ii-1,0], euc_dist(P[ii],Q[0]))
    for jj in range(1,len(Q)):
        ca[0,jj] = max(ca[0,jj-1], euc_dist(P[0],Q[jj]))
    for ii in range(1,len(P)):
        for jj in range(1,len(Q)):
            ca[ii,jj] = max(min(ca[ii-1,jj],
                                ca[ii-1,jj-1],
                                ca[ii,jj-1]),
                            euc_dist(P[ii],Q[jj]))
    return ca[-1,-1]
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.