PSO Coding Class Error

1 次查看(过去 30 天)
Ali Ali
Ali Ali 2018-3-4
Hi,
I Generating a PSO Coding and having some obstacles.. please, see below coding for main.m and particle.m (class) and CostFunction.m (function). I appreciate if someone can help me with the error shown below.
main.m
%% Initialization
% Parameters nPop = 50; MaxIt = 50; w = 1; c1 = 2; c2 = 2;
% Initialize Global Best globalbest = inf;
% Generate Particle Template sample_particle = particle();
% Create Population Array particle(nPop) = particle();
% Array to Hold Best Cost Value on Each Iteration BestCosts = zeros(MaxIt, 1);
%% Main Loop of PSO
for it=1:MaxIt
for i=1:nPop
% Update Velocity
particle(i).velocity = w*particle(i).velocity ...
+ c1*rand(particle(i).VarSize).*(particle(i).bestPosition - particle(i).position) ...
+ c2*rand(particle(i).VarSize).*(particle(i).globalbest - particle(i).position);
% Update Position
particle(i).position = particle(i).position + particle(i).velocity;
% Evaluation
particle(i) = CostFunction(particle(i).position);
% Update Personal Best
if particle(i).cost < particle(i).bestCost
particle(i).Best.Position = particle(i).position;
particle.Best.Cost = particle.Cost;
% Update Global Best
if particle(i).Best.Cost < globalbest.cost
globalbest.cost = particle.Best;
l
end
end
end
% Store the Best Cost Value
BestCosts(it) = globalbest;
%%Plotting the swarm
clf
plot(BestCosts, 'x') % drawing swarm movements
axis([-10 10 -10 10]);
pause(.1)
% Display Iteration Information
disp(['Iteration' num2str(it) ': Best Cost = ' num2str(BestCosts(it))]);
end
particle.m
classdef particle
properties
% Parameters
VarMin = -10;
VarMax = 10;
nVar = 1; % Number of Variables
VarSize = [1 nVar];
% Template
position = [];
velocity = [];
cost = [];
bestPosition = [];
bestCost = [];
% Initialize Global Best
globalbest = inf;
end
methods
function [ obj ] = particle( varargin )
% Generate Random Solution
obj.position = rand(obj.VarMin, obj.VarMax, obj.VarSize);
% Initialize Velocity
obj.velocity = zeros(obj.VarSize);
% Evaluation
obj.cost = CostFunction(obj.position);
% Update the Personal Best
obj.bestPosition = obj.position;
obj.bestCost = obj.cost;
% Update Global Best
if obj.bestCost < obj.globalbest
obj.globalbest = obj.bestCost;
end
end
end
end
CostFunction.m
function z = CostFunction(x)
z = (x.^2);
end
and the error that I got..
Error using main (line 17) Invalid default value for property 'VarSize' in class 'particle': Undefined function or variable 'nVar'.

回答(2 个)

younes youyou
younes youyou 2019-12-16
Do you have idea how can update two variable ?

Gnana Prasuna
Gnana Prasuna 2021-11-17
Error in pso1 (line 31)
if particle(i).Best.Cost < GlobalBest.Cost
I'm getting this error when ever I do other optimization techniques which is not sphere eg. for leon, easom etc

类别

Help CenterFile Exchange 中查找有关 Particle Swarm 的更多信息

标签

Community Treasure Hunt

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

Start Hunting!

Translated by