Index of element to remove exceeds matrix dimensions
1 vue (au cours des 30 derniers jours)
Afficher commentaires plus anciens
Can you tell me why this erreer massage is popping up in this program (Index of element to remove exceeds matrix dimensions.)
% Mutation and Crossover
for i = 1:Np
idx = 1:Np;
idx(i) = []; % Remove current solution from list
a = idx(randi(Np-1));
idx(a) = []; % Remove a from list
b = idx(randi(Np-2));
idx(b) = []; % Remove b from list
c = idx(randi(Np-3));
V = P(a,:) + F*(P(b,:) - P(c,:)); % Mutation
jrand = randi(D,1); % Random index for crossover
for j = 1:D
if (rand <= CR) || (j == jrand)
U(i,j) = V(j);
else
U(i,j) = P(i,j);
end
end
end
2 commentaires
John D'Errico
le 14 Mar 2023
Modifié(e) : John D'Errico
le 14 Mar 2023
Use the debugger. Set a breakpoint that will trigger on an error. Then look carefully at the variables involved in that line. As has been said, we can't debug code we can't run.
Réponse acceptée
Voss
le 14 Mar 2023
Let's examine what happens on the first iteration of that for loop.
for i = 1:Np
First time through the loop, i is 1.
idx = 1:Np;
idx is 1:Np.
idx(i) = []; % Remove current solution from list
First time through the loop, the 1st element of idx is removed, so idx is now 2:Np.
a = idx(randi(Np-1));
randi(Np-1) generates a random integer between 1 and Np-1, so a is a random element of idx. That is, a is one of 2,3,4,...,Np, which are the elements of idx.
idx(a) = []; % Remove a from list
This removes element #a fom idx, i.e., element #2 if a is 2, element #3 if a is 3, and so on. But if a happens to be Np, then there is no element #a in idx, and you get the error you got. Remember idx is 2:Np at this point, which is a vector of length Np-1. There is no element #Np.
b = idx(randi(Np-2));
idx(b) = []; % Remove b from list
The same error can happen when removing element #b, for the same reason.
c = idx(randi(Np-3));
% more stuff
end
I suspect that what you meant to do is:
for i = 1:Np
idx = 1:Np;
idx(i) = []; % Remove current solution from list
a = randi(Np-1); % random integer between 1 and Np-1 (not 2 to Np)
idx(a) = []; % Remove element #a from idx
b = randi(Np-2); % random integer between 1 and Np-2
idx(b) = []; % Remove element #b from idx
c = randi(Np-3); % random integer between 1 and Np-3
% more stuff
end
0 commentaires
Plus de réponses (0)
Voir également
Catégories
En savoir plus sur Linear Algebra dans Help Center et File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!