lancelotli 发表于 2017-1-21 22:01:03

优化算法案例分析与应用P169页

按书上代码,敲的,报错
Error using-
Matrix dimensions must agree.

Error in PSO_base1 (line 36)
       V(j, :) = V(j, :) +c1*rand*(gbest(j, :) -pop(j, :)) + c2*rand*(zbest -pop(j,
       :));

实在找不到错误在哪里。

求指点

Halcom 发表于 2017-1-21 22:27:37

检查变量:速度V、gbest、zbest的维度,贴出代码吧


或者直接看学习视频:
1粒子群算法 + (PPT+参考文献) + 源程序
2改进的粒子群算法(粒子群算法、线性权重递减PSO、线性权重递增PSO、惯性权重PSO(3种)、随机权重PSO、压缩因子PSO) + (PPT+参考文献) + 源程序

lancelotli 发表于 2017-1-22 16:50:53

Halcom 发表于 2017-1-21 22:27
速度V的维度声明错了,贴出代码吧,或者直接视频:




clc
clear all;
close all;
c1 = 1.49455;
c2 = 1.49455;

maxg = 200;
sizepop = 20;

%初始速度和种群上下边界
Vmax=1;
Vmin=-1;
popmax=5;
popmin=-5;

%产生粒子和速度
for i=1:sizepop
    %随机产生一个种群
    pop(i,:)=5*rands(1,2);%i是第行矩阵,列数待定。rands(1,2)产生一行两列。% 初始化种群
    V(i,:)=rands(1,2);%初始化速度
    %计算适应度
    fitness(i)=fun(pop(i,:));    %粒子的适应度值
end

%找最好的粒子
=min(fitness);%min返回两个数值 一个是数值最小的 一个是这个最小数值的位置
zbest = pop(bestindex, :);%全局最优x1与x2值
gbest=pop;%个体最优x1与x2值
fitnessgbest = fitness; %个体最佳适应度
fitnesszbest=bestfitness; %全局最佳适应度值

%%迭代寻优
for i=1:maxg
    for j=1:sizepop
      %速度更新
       V(j, :) = V(j, :) +c1*rand*(gbest(j, :) -pop(j, :)) + c2*rand*(zbest -pop(j, :));
      V(j,find(V(j,:)>Vmax)) =Vmax;% 如果X是一个逻辑表达式,则返回一个逻辑数组,一般如果存在满足要求的元素,则返回一个单位列向量
      V(j,find(V(j,:)<Vmin)) =Vmin;
      %种群更新
      pop(j,:) = pop(j,:) +0.5*V(j,:);
      pop(j, find(pop(j,:)>popmax)) = popmax;
      pop(j, find(pop(j,:)<popmin)) = popmin;
      
      %自适应变异
      if rand<0.8
            k = ceil(2*rand);%ceil取整
            pop(j,k) = rand;
      end
      %适应度值
      fitness(j)=fun(pop(j,:));
      
      %个体最优更新
      if fitness(j) < fitnessgbest(j)
            gbest(j,:) = pop(j,:);
            fitnessgbest(j) = fitness(j);
      end
      
      %群体最优更新
      if fitness(j) < fitnesszbest
            zbest(j,:) = pop(j,:);
            fitnesszbest= fitness(j);
      end
    end
    yy(i) = fitnesszbest;%保存每一代最优个体
end
%%结果分析
plot(yy,'linewidth',2)
title(['适应度曲线 ' '终止代数= ' num2str(maxg)]);
grid on
xlabel('进化代数'); ylabel(' 适应度');
%输出结果
zbest

Halcom 发表于 2017-1-22 16:55:09

lancelotli 发表于 2017-1-22 16:50
clc
clear all;
close all;

zbest(j,:) = pop(j,:);改为:
zbest = pop(j,:);

lancelotli 发表于 2017-1-22 19:35:33

Halcom 发表于 2017-1-22 16:55
zbest(j,:) = pop(j,:);改为:
zbest = pop(j,:);

多谢大神!代码已经正确运行!
页: [1]
查看完整版本: 优化算法案例分析与应用P169页