Index of element to remove exceeds matrix dimensions

1 view (last 30 days)
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 Comments
Dyuman Joshi
Dyuman Joshi on 14 Mar 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 on 14 Mar 2023
Edited: John D'Errico on 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.

Sign in to comment.

Accepted Answer

Voss
Voss on 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

More Answers (0)

Categories

Find more on Linear Algebra in Help Center and File Exchange

Community Treasure Hunt

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

Start Hunting!