# Index of element to remove exceeds matrix dimensions

5 次查看（过去 30 天）
ahmed mer2023-3-14

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 个评论显示 1更早的评论隐藏 1更早的评论
John D'Errico 2023-3-14

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.

### 采纳的回答

Voss 2023-3-14
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

### 类别

Find more on Descriptive Statistics 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!