1

I have a code in Matlab and I want to convert it to Python.

Matlab code:

...
...
for i=1:Z
        index=0;
        N_no=0;
        clear A
        clear B
        for j=1:Z
            Dist=distance(X(:,i),X(:,j));
            if (all(Dist<=r) && all(Dist~=0))
                index=index+1;
                N_no=N_no+1;
                A(:,index)=DeltaX(:,j);
                B(:,index)=X(:,j);
            end
        end
...
...

end

Python code:

for i in range(0, Z):
    index = -1
    N_no = -1
    A = np.zeros((Z, dim))
    B = np.zeros((Z, dim))
    for j in range(0, Z):
        Dist = Distance(X[i, :], X[j, :])
        if np.all(Dist <= r) and np.all(Dist != 0):
            index = index + 1
            N_no = N_no + 1
            A[index, :] = DeltaX[j, :]
            B[index, :] = X[j, :]
...

This code is working, but I am looking for an efficient way to convert it. I cannot use del A, del B in the Python code, instead of A = np.zeros((Z, dim)), B = np.zeros((Z, dim)), because I will get this error: UnboundLocalError: local variable 'A'/'B' referenced before assignment. Any suggestion?

1 Answer 1

2

This is the standard approach to assign an empty Numpy array. I would see no need of deleting the variable at all. I assume, that you don't use the variable 'A' and 'B' in the code above and thus the error message is also valid.

You can not delete a variable that does not exist.

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.