Reputation: 269
I am attempting to convert a script I have in MATLAB to Python in order to increase speed and efficiency of the overall algorithm. In MATLAB, the code is as follows:
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
I have completed most of the translation:
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
however, on line 11, I am returned an error of "index error: too many indices." What is causing Python to get tripped up on this line? How can I write my Python code so that I am not returning this error? index array is a numpy array predefined with length 16 with random integers 0-5, indexd array is a 16x16 array with random integers -5 to 5, and indexdn,indadd are being created within this iteration.
Upvotes: 2
Views: 83
Reputation: 69116
It looks like index
is a 1-d array? (you have index[y]
and index[x]
on line 5 and 8, and say it is of length 16)
But, on line 11, you are trying to access its second dimension: index[y,:]
. Maybe that should be indexdn[y,:] =-indexdn[:,y]
?
Upvotes: 3