gpt4 book ai didi

python - 将 MATLAB 转换为 Python : too many indices return error

转载 作者:太空宇宙 更新时间:2023-11-04 01:05:31 24 4
gpt4 key购买 nike

我正在尝试将 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 正在本次迭代中创建。

最佳答案

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

但是,在第 11 行,您正试图访问它的第二个维度:index[y,:]。也许那应该是 indexdn[y,:] =-indexdn[:,y]

关于python - 将 MATLAB 转换为 Python : too many indices return error,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30670169/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com