Index of element to remove exceeds matrix dimensions

1 visualización (últimos 30 días)
ahmed mer
ahmed mer el 14 de Mzo. de 2023
Respondida: Voss el 14 de Mzo. de 2023
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 comentarios
Dyuman Joshi
Dyuman Joshi el 14 de Mzo. de 2023
There are undefined variables in your code and thus we can't run the code.
Please update your code. Also, mentioned the full error message, that means all the red text.
John D'Errico
John D'Errico el 14 de Mzo. de 2023
Editada: John D'Errico el 14 de Mzo. de 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.

Iniciar sesión para comentar.

Respuesta aceptada

Voss
Voss el 14 de Mzo. de 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

Más respuestas (0)

Categorías

Más información sobre Linear Algebra en Help Center y File Exchange.

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by