1

我在 Matlab 中有一个代码,我想将其转换为 Python。

Matlab代码:

...
...
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代码:

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, :]
...

此代码有效,但我正在寻找一种有效的方法来转换它。我不能在 Python 代码中使用 , 而不是del A,因为我会得到这个错误:. 有什么建议吗?del BA = np.zeros((Z, dim))B = np.zeros((Z, dim))UnboundLocalError: local variable 'A'/'B' referenced before assignment

4

1 回答 1

2

这是分配空 Numpy 数组的标准方法。我认为根本不需要删除变量。我假设您没有在上面的代码中使用变量“A”和“B”,因此错误消息也是有效的。

您不能删除不存在的变量。

于 2020-10-12T07:17:31.400 回答