Error existent field - classes
2 次查看(过去 30 天)
显示 更早的评论
I've coded PSO Simulink, and make particle as a class, main coding as below:
clc;
clear;
close all;
%%Initialization
% Parameters
nPop = 50;
MaxIt = 100;
w = 1;
c1 = 2;
c2 = 2;
% Generate Particle Template
sample_particle = particle();
% Create Population Array
particles(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).Cost = CostFunction(particle(i).position);
% Update Personal Best
if particle.Cost < particle.Best.Cost
particle.Best.Position = particle.position;
particle.Best.Cost = particle.Cost;
% Update Global Best
if particle.Best.Cost < GlobalBest.Cost
GlobalBest = particle.Best;
end
end
end
% Store the Best Cost Value
BestCosts(it) = GlobalBest.Cost;
% Display Iteration Information
disp(['Iteration' num2str(it) ': Best Cost = ' num2str(BestCosts(it))]);
end
And Class coding:
classdef particle
%PARTICLES Summary of this class goes here
% Detailed explanation goes here
properties
% Parameters
VarMin = -10;
VarMax = 10;
VarSize = 2;
% Template
position = [];
velocity = [];
cost = [];
bestPosition = [];
bestCost = [];
% Initialize Global Best
globalbest = inf;
end
methods
function [ obj ] = particle( varargin )
function circle = CostFunction(x,y)
circle = (x.^2)+(y.^2);
end
% Generate Random Solution
obj.position = unifrnd(obj.VarMin, obj.VarMax, obj.VarSize);
% Initialize Velocity
obj.velocity = zeros(obj.VarSize);
% Evaluation
obj.cost = CostFunction(obj.position,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
then, after run got an error:
Reference to non-existent field 'position'.
Error in main (line 35)
particle(i).position = particle(i).position + particle(i).velocity;
and I want to plot swarm particles on its moving motion.
0 个评论
采纳的回答
Steven Lord
2018-2-20
Don't define a variable in your code with the same name as a function or class you want to use in that code.
Change the variable name particle in your PSO code to particles (which I would avoid as too easy for a human to mistype or misread as particle) or something like listOfParticles and make that an array of particle objects.
更多回答(0 个)
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Surrogate Optimization 的更多信息
产品
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!