将MATLAB转换为Python:返回的索引太多

2024-04-16 16:52:53 发布

您现在位置:Python中文网/ 问答频道 /正文

为了提高整个算法的速度和效率,我正在尝试将MATLAB中的一个脚本转换为Python。在MATLAB中,代码如下:

for iter = 1:T
costi = costo;
for i = 1:length(index)
    for j = i+1:length(index)
        if index(j) == index(i)
            continue;
        end
        indexdn = indexd;
        indadd = (index(j) - index(i));
        indexdn(:,j) = indexdn(:,j) + indadd;
        ##line 11
        indexdn(j,:) = -indexdn(:,j)';            
        indexdn(j,j) = 0;
        indi = abs(indexdn);
        indi = ~indi;
        costnb = costmata.*indi;
        costn = 0.5*(sum(sum(costnb)));
        if costn < costi
            costi = costn;
            index(j) = index(i);
            indexd = indexdn;
        end
    end
end
if costi < costo
    costo = costi;
else 
    break
end
iter
end

我已经完成了大部分翻译:

for j in range(0,T):
cost2 = cost1
for x in xrange(len(index)):
    for y in xrange(x+1,len(index)):
        if index[y] == index[x]:
            continue
        indexdn = indexd
        indadd= index[y]-index[x]
        print indadd
        indexdn[:,y]=indexdn[:,y]+ indadd
        index[y,:]=-indexdn[:,y] ##line 11, return error
        indexdn[y,y]=0
        indi= np.abs(indexdn)
        indi= ~indi
        costnb = costmata*indi
        costn = .5(np.sum(costnb))
        if (costn < cost2):
            costi=costn;
            index[y] = index[x]
            indexd= indexdn
if cost2<cost1:
    cost1=cost2
else:
    break

然而,在第11行,我返回了一个错误“index error:too many index.”是什么导致Python在这一行被绊倒?如何编写Python代码以避免返回此错误?index数组是一个预定义的numpy数组,长度为16,随机整数为0-5,indexd数组是一个16x16数组,随机整数为-5到5,indexdn,indadd在此迭代中创建。你知道吗


Tags: forindexif数组endsumindicost2
1条回答
网友
1楼 · 发布于 2024-04-16 16:52:53

看起来index是一维数组?(第5行和第8行有index[y]index[x],长度为16)

但是,在第11行,您试图访问它的第二维度:index[y,:]。也许应该是indexdn[y,:] =-indexdn[:,y]?你知道吗

相关问题 更多 >