【发布时间】:2015-08-20 14:51:10
【问题描述】:
我正在尝试将我在 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 行,我返回了“索引错误:索引过多”的错误。是什么导致 Python 在这条线上被绊倒?如何编写我的 Python 代码,以免返回此错误? index 数组是一个 numpy 数组,预定义长度为 16,随机整数 0-5,indexd 数组是一个 16x16 数组,随机整数 -5 到 5,indexdn ,indadd 正在此迭代中创建。
【问题讨论】:
-
翻译这样的迭代不会提高速度。现代 MATLAB 像这样“编译”循环。 Python/numpy 与旧 MATLAB 版本一样,需要“矢量化”才能达到其速度。
-
我不知道这是否会影响您的错误,但您的 Matlab 代码中有
indexdn(j,:) = -indexdn(:,j)'(转置)但在您的 python 中没有。
标签: python arrays matlab numpy indexing