简体   繁体   中英

Passing additional arguments through function handle in Matlab

I have a function to optimize, say Function, in Matlab. This function depends on variables (say x) over which I want to optimize and one parameter (say, Q) which does not need to be optimized.Hence, the function Function(x,Q). In other words, I have an array of values for Q and want to find optimal x values for each Q. However, I cannot find a way how to pass those Q values when using function handle @Function in optimization function.

So, my question is how to pass those Q values when using function handle in optimization functions, for example fmincon(@Function,x0,A,b)?

Try using anonymous function:

x = cell( 1, numel(Q) );
for qi = 1:numel( Q )
   x{qi} = fmincon( @(x) Function(x, Q(qi)), A, b );
end 

As described in MATLAB documentation, there are actually 3 solutions for this problem:

  1. Anonymous Functions
    which is described in the Shai's answer of this post.
  2. Nested Functions :
    in this approach the outer function accepts all arguments, and the inner function only accepts parameters that optimization takes place on them.
    this is an example taken from MATLAB documentation: function [x,fval] = runnested(a,b,c,x0) [x,fval] = fminunc(@nestedfun,x0); % Nested function that computes the objective function function y = nestedfun(x) y = (a - b*x(1)^2 + x(1)^4/3)*x(1)^2 + x(1) x(2) +... (-c + c x(2)^2)*x(2)^2; end end function [x,fval] = runnested(a,b,c,x0) [x,fval] = fminunc(@nestedfun,x0); % Nested function that computes the objective function function y = nestedfun(x) y = (a - b*x(1)^2 + x(1)^4/3)*x(1)^2 + x(1) x(2) +... (-c + c x(2)^2)*x(2)^2; end end
  3. Global Variables
    in this approach you should define the parameters that are needed in objective function as global in workspace, and use them in objective function with declaring them as global.
    here is an example again from MATLAB documentation:
    • Defining objective function: function y = globalfun(x) global abcy = (a - b*x(1)^2 + x(1)^4/3)*x(1)^2 + x(1) x(2) + ... (-c + c x(2)^2)*x(2)^2; end function y = globalfun(x) global abcy = (a - b*x(1)^2 + x(1)^4/3)*x(1)^2 + x(1) x(2) + ... (-c + c x(2)^2)*x(2)^2; end
    • Optimization: global abc; a = 4; b = 2.1; c = 4; % Assign parameter values x0 = [0.5,0.5]; [x,fval] = fminunc(@globalfun,x0) global abc; a = 4; b = 2.1; c = 4; % Assign parameter values x0 = [0.5,0.5]; [x,fval] = fminunc(@globalfun,x0)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM