2015-06-05 50 views
2

我試圖將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正在這個迭代內創建的。

+1

像這樣翻譯迭代不會提高速度。現代MATLAB'編譯'這樣的循環。 Python/numpy像舊版本的MATLAB一樣,需要「矢量化」來實現其速度。 – hpaulj

+1

我不知道這是否會影響你的錯誤,但是你在你的Matlab代碼中有'indexdn(j,:) = -indexdn(:,j)''(轉置),但不是在你的python中。 – Scott

回答

3

看起來像index是一維數組? (在第5行和第8行上有index[y]index[x],並且它的長度是16)

但是,在第11行上,您嘗試訪問其第二維:index[y,:]。也許應該是indexdn[y,:] =-indexdn[:,y]

+0

加1 - 我同意。 – rayryeng

+0

非常感謝。啊,打字很難。 –