Index of element to remove exceeds matrix dimensions

조회 수: 1 (최근 30일)
ahmed mer
ahmed mer 2023년 3월 14일
답변: Voss 2023년 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
Dyuman Joshi
Dyuman Joshi 2023년 3월 14일
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 2023년 3월 14일
편집: 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
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

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Linear Algebra에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by