SHdotCom
SHdotCom

Reputation: 193

An efficient way to convert a Matlab code to Python

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?

Upvotes: 1

Views: 106

Answers (1)

elyptikus
elyptikus

Reputation: 1148

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.

Upvotes: 2

Related Questions