我试图将MATLAB中的脚本转换为Python以提高整体算法的速度和效率。在MATLAB,代码如下:将MATLAB转换为Python:太多索引返回错误
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行,我现在回到“指数错误的错误:太多的指标“。什么导致Python在这条线上被绊倒?我怎样才能写我的Python代码,以便我不返回这个错误? 索引阵列是预定义长度为16个随机整数0-5 numpy的阵列,indexd阵列是16×16阵列的随机整数-5至5,和indexdn,indadd正在这个迭代内创建的。
像这样翻译迭代不会提高速度。现代MATLAB'编译'这样的循环。 Python/numpy像旧版本的MATLAB一样,需要“矢量化”来实现其速度。 – hpaulj
我不知道这是否会影响你的错误,但是你在你的Matlab代码中有'indexdn(j,:) = -indexdn(:,j)''(转置),但不是在你的python中。 – Scott