JuanMuñoz
JuanMuñoz

Reputation: 164

How to use Particle Swarm Optimization calling a function from a script

I want to use PSO in the following structure:

lb = [-10,-15];
ub = [15,20];
options = optimoptions('particleswarm','SwarmSize',100,'HybridFcn',@fmincon);
rng default  % For reproducibility
nvars = 2;

x = particleswarm(fun,nvars,lb,ub)

Where fun is saved in other script with the following structure

function y = fun(x)

y = x(1)*exp(-norm(x)^2);
end

But it is not working. I can see that PSO work if I save fun in the same code:

lb = [-10,-15];
ub = [15,20];
fun = @(x)x(1)*exp(-norm(x)^2);
options = optimoptions('particleswarm','SwarmSize',100,'HybridFcn',@fmincon);
rng default  % For reproducibility
nvars = 2;
x = particleswarm(fun,nvars,lb,ub)

But this is not what I am looking for. I am looking for applying swarm in a function saved in another script. How could I make PSO work in this sense?

Upvotes: 0

Views: 362

Answers (1)

rinkert
rinkert

Reputation: 6863

Just add an @:

x = particleswarm(@fun,nvars,lb,ub)

This makes sure that you are giving the optimizer the handle to the function fun, and not evaluate the function without any input parameters. See the Matlab docs on function handles.

Upvotes: 1

Related Questions