m0_62740426 2022-08-10 15:35 采纳率: 33.3%

# 位置 1 中的索引超过数组边界（不得超过 1报错

clc
clear

c1 = 1.4955;
c2 = 1.4955;
w = 1;

maxgen = 100;
sizepop = 50;
nvar = 2;
vmax = 5 ;
vmin = -5;
popmax = 100;
popmin = -100;
pbest = [];
for i = 1 : sizepop
pop(i,:) = (popmax-popmin) * rand(1,nvar) + popmin;
V(i,:) = (vmax-vmin) * rands(1,nvar) + vmin;
funtion(i) = fun(pop(i,:));
fitness(i) = 1/funtion(i);
end
[bestfitness,bestindex] = max(fitness);
bestfuntion = funtion(bestindex);
bestpop = pop(bestindex,:);
pbest = pop;
pbestfuntion = funtion;
pbestfitness = fitness;

for i = 1 : maxgen

for j = 1 : sizepop
V(j,:) = w.V(j,:) + c1rand*(pbest(j,:)-pop(j,:))+c2rand(bestpop-pop(j,:));

``````    V(j, find(V(j,:)) > vmax) = vmax;
V(j, find(V(j,:)) < vmin) = vmin;

pop(j,:) = pop(j,:) + V(j,:);

pop(j,find(pop(j,:) > popmax)) = popmax;
pop(j,find(pop(j,:) < popmin)) = popmin;
funtion(j) = fun(pop(j,:));
fitness(j) = 1/funtion(j);

``````

end
for j = 1 : sizepop
if fitness(j) > pbestfitness(j)
pbestfitness(j) = fitness(j);
pbestfuntion(j) = funtion(j);
pbest = pop(j,:);

``````   end
if   fitness(j) > bestfitness
bestfitness = fitness(j);
bestfuntion = funtion(j);
bestpop = pop(j,:);
end
``````

end

end

• 写回答

#### 1条回答默认 最新

• falwat 2022-08-10 15:49
关注

不好排查问题出在哪儿。建议你自己在出错的地方设置一个断点，然后在命令窗口里依次测试表达式的每个运算

本回答被题主选为最佳回答 , 对您是否有帮助呢?
评论

• 系统已结题 8月18日
• 已采纳回答 8月10日
• 创建了问题 8月10日