简体   繁体   中英

MATLAB fmincon with gradient vector

I would like to use MATLAB function fmincon using a gradient vector only (without scalar function). But I have trouble with it. For instance, I tried the following, but it doesn't work. Any help please? Thanks!

    fun = @rosenbrockwithgrad;
    x0 = [-1,2];
    A = [];
    b = [];
    Aeq = [];
    beq = [];
    lb = [-2,-2];
    ub = [2,2];
    x = fmincon(fun,x0,A,b,Aeq,beq,lb,ub)   


function [grad] = rosenbrockwithgrad(x) 
 grad = [-400*(x(2)-x(1)^2)*x(1)-2*(1-x(1));
            200*(x(2)-x(1)^2)];
 end

You need to include both the function and its gradient. See below:

options = optimoptions('fmincon','SpecifyObjectiveGradient',true);
fun = @rosenbrockwithgrad;
x0 = [-1,2];
A = [];
b = [];
Aeq = [];
beq = [];
lb = [-2,-2];
ub = [2,2];
nonlcon = [];
x = fmincon(fun,x0,A,b,Aeq,beq,lb,ub,nonlcon,options)


function [f,g] = rosenbrockwithgrad(x)
    % Calculate objective f
    f = 100*(x(2) - x(1)^2)^2 + (1-x(1))^2;

    if nargout > 1 % gradient required
        g = [-400*(x(2)-x(1)^2)*x(1)-2*(1-x(1));
            200*(x(2)-x(1)^2)];
    end

end

This code should run properly.

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