why does this code give an error ( Undefined function or variable 'ObjectiveFunction'. Error in psi_kozhin (line 44) Swarm.Particles(k).O = fobj(currentX); )?
14 views (last 30 days)
Show older comments
clear all
close all
clc
% Define the details of the table design problem
nVar = 2;
ub = [10 10];
lb = [-10 -10];
fobj = @ObjectiveFunction;
% Define the PSO's paramters
noP = 30;
maxIter = 50;
wMax = 0.9;
wMin = 0.2;
c1 = 2;
c2 = 2;
vMax = (ub - lb) .* 0.2;
vMin = -vMax;
% The PSO algorithm
% Initialize the particles
for k = 1 : noP
Swarm.Particles(k).X = (ub-lb) .* rand(1,nVar) + lb;
Swarm.Particles(k).V = zeros(1, nVar);
Swarm.Particles(k).PBEST.X = zeros(1,nVar);
Swarm.Particles(k).PBEST.O = inf;
Swarm.GBEST.X = zeros(1,nVar);
Swarm.GBEST.O = inf;
end
% Main loop
for t = 1 : maxIter
% Calcualte the objective value
for k = 1 : noP
currentX = Swarm.Particles(k).X;
Swarm.Particles(k).O = fobj(currentX);
% Update the PBEST
if Swarm.Particles(k).O < Swarm.Particles(k).PBEST.O
Swarm.Particles(k).PBEST.X = currentX;
Swarm.Particles(k).PBEST.O = Swarm.Particles(k).O;
end
% Update the GBEST
if Swarm.Particles(k).O < Swarm.GBEST.O
Swarm.GBEST.X = currentX;
Swarm.GBEST.O = Swarm.Particles(k).O;
end
end
% Update the X and V vectors
w = wMax - t .* ((wMax - wMin) / maxIter);
for k = 1 : noP
Swarm.Particles(k).V = w .* Swarm.Particles(k).V + c1 .* rand(1,nVar) .* (Swarm.Particles(k).PBEST.X - Swarm.Particles(k).X) ...
+ c2 .* rand(1,nVar) .* (Swarm.GBEST.X - Swarm.Particles(k).X);
% Check velocities
index1 = find(Swarm.Particles(k).V > vMax);
index2 = find(Swarm.Particles(k).V < vMin);
Swarm.Particles(k).V(index1) = vMax(index1);
Swarm.Particles(k).V(index2) = vMin(index2);
Swarm.Particles(k).X = Swarm.Particles(k).X + Swarm.Particles(k).V;
% Check positions
index1 = find(Swarm.Particles(k).X > ub);
index2 = find(Swarm.Particles(k).X < lb);
Swarm.Particles(k).X(index1) = ub(index1);
Swarm.Particles(k).X(index2) = lb(index2);
end
outmsg = ['Iteration# ', num2str(t) , ' Swarm.GBEST.O = ' , num2str(Swarm.GBEST.O)];
disp(outmsg);
cgCurve(t) = Swarm.GBEST.O;
end
semilogy(cgCurve);
xlabel('Iteration#')
ylabel('Weight')
0 Comments
Answers (1)
Alan Weiss
on 18 Mar 2021
I do not see where you defined ObjectiveFunction. Is it on your MATLAB path?
Alan Weiss
MATLAB mathematical toolbox documentation
0 Comments
See Also
Categories
Find more on Matrix Indexing 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!