# Writing an Optimization Problem

6 views (last 30 days)
Nouman Khan on 23 May 2020
Commented: Nouman Khan on 23 May 2020
I am trying to solve a non-linear optimization problem, i.e. to maximize
subject to .
I have made a separate function file nlconstraints with the following content.
function [c,ceq] = nlconstraints(x,y)
c(1)=1-x;
c(2)=1-y;
c(3)=y-x;
ceq=[];
end
I have the following code in my original file (which is in the same folder as the function file)
clear all
clc
fun = @(x,y)-x*(1+2*y)*exp(-y*x^(0.9));
nonlcon = @nlconstraints;
x0 = [1.12 1];
A = []; % No other constraints
b = [];
Aeq = [];
beq = [];
lb = [];
ub = [];
x = fmincon(fun,x0,A,b,Aeq,beq,lb,ub,nonlcon)
I am getting the following errors.
Not enough input arguments.
Error in max_drift_non_rare (line 50)
fun = @(x,y)-x*(1+2*y)*exp(-y*x^(0.9));
Error in fmincon (line 562)
initVals.f = feval(funfcn{3},X,varargin{:});
Error in max_drift_non_rare (line 59)
x = fmincon(fun,x0,A,b,Aeq,beq,lb,ub,nonlcon)
Would someone kindly help. Thank you.

Gautam on 23 May 2020
I know you want to find optimal values of x&y, but while using fmincon or any of the optimization routines, you should pass only one input argument to an objective function.
Replace:
fun = @(x,y)-x*(1+2*y)*exp(-y*x^(0.9)); % Your original code
with
fun = @(x) -x(1)*(1+2*(x(2)))*exp(-x(2)*(x(1))^0.9); % Where MATLAB will assume x(1) is x and x(2) is y;
Similarly change the constraint function 'nlconstraints' to take in one input argument 'x' and in your function body rewrite y as x(2), and x as x(1). For ex: Replace c(1)=1-x with c(1)=1-x(1);
Nouman Khan on 23 May 2020
Thank you! This was exactly the correction I needed.

Gifari Zulkarnaen on 23 May 2020
Edited: Gifari Zulkarnaen on 23 May 2020
I am not sure why yours doesnt work, but it works if the functions are written in array form like this:
clear
fun = @(x) (x(1)*(1+2*x(2))*exp(-x(2)*x(1)^(0.9));
x0 = [1.12 1];
x = fmincon(fun,x0,[],[],[],[],[],[],@nlconstraints);
function [c,ceq] = nlconstraints(x)
c(1)=1-x(1);
c(2)=1-x(2);
c(3)=x(2)-x(1);
ceq=[];
end
Nouman Khan on 23 May 2020
Thank you! This was exactly the correction I needed.

### Categories

Find more on Solver Outputs and Iterative Display in Help Center and File Exchange

R2020a

### Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!