Search code examples
matlaboptimizationdifferential-equations

Single calculation for objective function and constraints function in fmincon


In my program I need to solve a Boundary Value Problem in the optimization routine which also has non linear constraints. Using fmincon for the problem and i need the solution of the BVP to evaluate the objective function and the non linear constraint function.

Currently I am solving the BVP in objective function and also in constraint function. Is there a more efficient way in which after one evaluation of the BVP in objective function, I can pass the solution to the constraint function in order to reduce one more BVP evaluation. Any ideas


Solution

  • Create a single function with an extra input, which you use to discriminate between the two calls. This is basically a wrapper around the objective and constraint functions, saving all necessary intermediate output in persistent variables:

    function varargout = my_obj_con_function(..., option)
    
        persistent C, Ceq; % ... or any other data you might need
    
        switch (option)
    
            case 'obj'
    
                % objective function 
                [varargout{1}, data] = objfun(...); % 'data' is an example
    
                % constraint function 
                [C, Ceq] = confcn(data, ...);
    
            case 'con'
    
                % You've just computed this -- just return it
                varargout{1} = C;
                varargout{2} = Ceq;
                return 
    
        end
    
    end
    

    Use like this:

    [...] = fmincon(@(x) my_obj_con_function(x, ..., 'obj'), ...
                    x0,...
                    Lb, Ub, ...
                    A, b,...
                    Aeq, beq, ...
                    @(x) my_obj_con_function(x, ..., 'con'), ...);
    

    This explicitly assumes that fmincon always calls the constraint function after calling the objective function, with exactly the same values for the decision variables. Now I'm not sure if that can be guaranteed -- you might want to build in some protections and mechanisms around when that is not the case.