MATLAB: Undefined operator ‘<' for input arguments of type 'struct'

structundefined operator

Hi all,
I'm new to doing PSO on MATLAB. I'm currently facing this problem where I couldn't do a "<" operation on 2 struct arguments as seen in Line 48. This is just a section of the code I'm referencing online. Any help would be highly appreciative. Thanks!

Best Answer

Explanation
This error occurs because GlobalBest.Cost is a structure.
Before the loop you defined GlobalBest.Cost to be Inf, so on the first loop iteration you compare Inf against particle(1).Best.Cost, which we can presume is numeric (if the output of CostFunction is numeric). The first time that this comparison is true, the code inside the if will be evaluated, and you replace the Inf value like this:
GlobalBest.Cost = particle(i).Best % RHS is a structure!
Note that particle(i).Best is a structure with two fields (named Position and Cost). So now GlobalBest.Cost is a structure (you can check this quite easily yourself). Then on the second loop iteration, you try comparing this structure using <, which throws the error.
Solution
The solution is very simple, you just need this:
GlobalBest.Cost = particle(i).Best.Cost % RHS is a numeric!
Or you could write simpler MATLAB code and replace the entire if with min..