PSO (particle swarm optimization) Error Coding

I've coded a PSO as below:
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.Cost
obj.GlobalBest = obj.GlobalBest.best;
end
end
end
end
and have an error:
Struct contents reference from a non-struct array object.
Error in particle (line 51)
if obj.bestCost < obj.GlobalBest.Cost

 採用された回答

Walter Roberson
Walter Roberson 2018 年 2 月 18 日

2 投票

You have
GlobalBest = inf;
so GlobalBest is numeric, not a struct.

6 件のコメント

Ali Ali
Ali Ali 2018 年 2 月 18 日
Okay.. and what should I do?
Ali Ali
Ali Ali 2018 年 2 月 18 日
I've removed (.cost) from (GlobalBest) and it works, so, if that what you mean.. thank you.
Walter Roberson
Walter Roberson 2018 年 2 月 18 日
What you needed to do was be consistent in the data type of the variables. You solved it one way, and another way would have been to initialize to a struct instead of to numeric.
Ali Ali
Ali Ali 2018 年 2 月 20 日
Okay, what is your recommendation?
Walter Roberson
Walter Roberson 2018 年 2 月 20 日
I am not sure that you need to make any more changes.
Ali Ali
Ali Ali 2018 年 2 月 20 日
I appreciate this.

サインインしてコメントする。

その他の回答 (0 件)

カテゴリ

タグ

質問済み:

2018 年 2 月 18 日

コメント済み:

2018 年 2 月 20 日

Community Treasure Hunt

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

Start Hunting!

Translated by