I am trying to solve an optimization problem in MATLAB with the function fmincon, but there appears a problem with the nonlinear constraints, as MATLAB tells that there are not enough input arguments.
This is my nlcon funtion:
function [c,ceq] = nlcon(w_md2,std)
c =[];
ceq = w_md2'*std-1;
end
that's the execution of fmincon:
covMat = cov(mon_ret) ;
[corMat, std] = corrcov(covMat);
w0 = repmat(n1, port_size, 1);
md2function = #(w_md2) md2(covMat, w_md2);
nonlincon = #nlcon;
w_md_2 = fmincon(md2function, w0, [], [], Aeq, Beq, lbnds, ubnds, nonlincon)
and that`s the error:
Not enough input arguments.
Error in nlcon (line 3)
ceq = w_md2'*std-1;
Error in fmincon (line 639)
[ctmp,ceqtmp] = feval(confcn{3},X,varargin{:});
Error in main (line 60)
w_md_2 = fmincon(md2function, w0, ...
Caused by:
Failure in initial nonlinear constraint function evaluation. FMINCON cannot continue.
Would be really glad if someone could help as I am at total newby to MATLAB.
Best regards
The documentation says that the function passed as argument nonlincon should take one input argument. That means that it is called with only one input argument, and std remains undefined.
You probably want to do
nonlincon = #(x)nlcon(x,std);
That way you create an anonymous function that takes one input argument, and calls your function with the value of std you computed earlier.
Related
I'm trying to solve a system of non linear odes in Matlab as follows.
editparams %parameters
Tend = 50;
Nt = 100;
% Define RHS functions
RHS = #(t,x) ModelRHS(t,x,param); %anonymous function defining the set of equations
%Execution-----------------------------------------------------------------
x0 =[0.04;0.75;0.85]; %Initial condition
t = linspace(0,Tend,Nt); %TSPAN
[t x] = ode45(RHS, t, x0);
Now, I need to find the steady state of the system and I'm trying to create a function for this. I thought I'd calculate the steady state using the Jacobian. My equations are in an anonymous function which is defined as f in the code below. However, I realised that jacobian does not work for anonymous functions (or may be there is a way to do with anonymous functions) . so I thought I would convert the anonymous function to a symbolic function and try it. But
i still have a difficulty in getting that done. So any help is really appreciated!
function SS = SteadyState(param, E)
f = #(t,x)ModelRHS(t,x,param,E); %set of odes
SymbolicSystem = sym(f); %trying to make the anonymous function symbolic
SymbolicJacobian = jacobian(SymbolicSystem',x); %jacobian
Jacob = matlabFunction(SymbolicJacobian,x);
end
Also if there is any other way apart from finding the Jacobian, kindly let me know about that too.
I tried using 'fsolve' to calculate the steady-state as follows:
f = #(t,x)ModelRHS(t,x,param);
x0 =[0.04;0.75;0.85]';
options = optimoptions('fsolve','Display','iter'); % Option to display output
SS = fsolve(f,x0,options); % Call solver
but it returned an error
Not enough input arguments.
Error in #(t,x)ModelRHS(t,x,param)
Error in fsolve (line 242)
fuser = feval(funfcn{3},x,varargin{:});
Caused by:
Failure in initial objective function evaluation. FSOLVE cannot continue.
I have written a simple optimization code using genetic algorithm.I don't know why I get error during running the code.Here is my code:
f = #(x1,x2) 1-x1.^2+(x1-x2).^2;
A = [1 1;-1 2;2 1];
b =[2 2 3]' ;
Aeq = [];
beq = [];
Lb = [0 0]';
Ub = [];
[Xopt,Fval] = ga(f,2,A,b,Aeq,beq,Lb,Ub)
I don not know why matlab gives me error.I wrote this programm based on the "Genetic algorithm Documentation" bit still gives me error:
Error using #(x1,x2)1-x1.^2+(x1-x2).^2
Not enough input arguments.
Error in createAnonymousFcn>#(x)fcn(x,FcnArgs{:}) (line 11)
fcn_handle = #(x) fcn(x,FcnArgs{:});
Error in makeState (line 48)
firstMemberScore = FitnessFcn(state.Population(initScoreProvided+1,:));
Error in galincon (line 18)
state = makeState(GenomeLength,FitnessFcn,Iterate,output.problemtype,options);
Error in ga (line 351)
[x,fval,exitFlag,output,population,scores] = galincon(FitnessFcn,nvars, ...
Caused by:
Failure in initial user-supplied fitness function evaluation. GA cannot continue
Objective functions of all optimization methods in MATLAB only accept 1 argument. According to ga documents:
fun — Objective function
Objective
function, specified as a function handle or function name. Write the
objective function to accept a row vector of length nvars and return a
scalar value.
When the 'UseVectorized' option is true, write fun to accept a
pop-by-nvars matrix, where pop is the current population size. In this
case, fun returns a vector the same length as pop containing the
fitness function values. Ensure that fun does not assume any
particular size for pop, since ga can pass a single member of a
population even in a vectorized calculation.
Change you objective function and it should work:
f = #(x) 1-x(1).^2+(x(1)-x(2)).^2;
I am solving a very simple constrained optimization problem. At this point, I have only entered a constraint that makes the (L-2) vector norm equal 1 and later I hope to add non-negativity constraints.
Fmincon is giving me a "Too many output arguments" on the my constraint. I don't understand why.
Objective function: A simple Quadratic form. Actually a variance covariance Matrix, I am entering as a pre-calculated global variable.
function [y, grady] = quadobj(x)
global Q
y = x*Q*x';
if nargout > 1
grady = 2*Q*x;
end
Equality Constraint: that vector L2 norm should be 1.
function outeq = confuneq2(x)
% Nonlinear equality constraints
outeq = x*x'-1;
end
Fmincon.
x0 = [0.7,0.1, -0.69];
options = optimoptions(#fmincon,'Algorithm','sqp');
[x,fval] = fmincon(#quadobj,x0,[],[],[],[],[],[],...
#confuneq2,options);
But it's not working. I am getting the following error.
Error using confuneq2
Too many output arguments.
Error in fmincon (line 632)
[ctmp,ceqtmp] = feval(confcn{3},X,varargin{:});
Caused by:
Failure in initial user-supplied nonlinear constraint function evaluation. FMINCON cannot continue
Please help!
Confusingly, the problem is that your function has too few output arguments. If you look at the error, it is telling you that MATLAB is trying to call your function with two output arguments but you've programmed it to take only one. Thus it errors because it has called your function with too many output arguments.
All the examples in the docs have two outputs so try create your function this way:
function [out, outeq] = confuneq2(x)
out = x*x'-1;
outeq = [];
end
I have a function of 2 different vector. These are the control vector (decision variables) of the function. I want to use fmincon to optimize this function and also get the both control vector results separately.
I have tried to use handle ,#, but I got an error.
The function is:
function f = myFS(x,sv) % x is a vector (5,1)
f = norm(x)^2-sigma*(sv(1)+sv(2));
end
%% I tried to write fmincone to consider both control vectors (x and sv)
[Xtemp(:,h2),Fval, fiasco] = fmincon(#(x,sv)myFS(x,sv)...
,xstart,[],[],[],[],VLB,VUB,#(x,sv)myCon(sv),options);
Here is the error I get:
Error using myFS (line 12) Not enough input arguments.
Error in fmincon (line 564)
initVals.f =
feval(funfcn{3},X,varargin{:});
Error in main_Econstraint (line 58) [Xtemp(:,h2),Fval, fiasco] =
fmincon('myFS',xstart,[],[],[],[],VLB,VUB,#(x,sv)myCon(sv),options);
Thanks
fmincon expects your function to be of a single variable, there is no getting around that, but see:
http://se.mathworks.com/help/optim/ug/passing-extra-parameters.html
for example, if both x, cv are variables of the optimization you can combine them and then split them in the actual objective
for example
x_cv = vertcat(x, cv) and then x = x_cv(1:5); cv = x_cv(6:end)'
if cv is not a variable of the optimization, then 'freeze it' as the link above suggests
I am facing an error when using the function fminunc in the context of a maximum-likelihood estimation. I am afraid that it is very straight forward however my experience with MATLAB is very limited.
The function "normal" contains the log-likelihood function. I seek to estimate the expectation and std. deviation of a normal distribution given the observations stored in the variable x.
function f = normal(X, theta)
mean = theta(1);
sigma = theta(2);
z = (X-mean)./sigma;
f = -(sum(-log(sigma) -(1/2).*z.^2 ));
I basically execute the following code:
theta = [1,1]
f = #(theta)normal(x, theta)
[est, fval, exitflag, output, grad, hessian] = fminunc('normal', x, theta)
The error is the following:
Warning: Struct field assignment overwrites a value with class "double". See MATLAB R14SP2 Release
Notes, Assigning Nonstructure Variables As Structures Displays Warning, for details.
In createOptionFeedback at 34
In prepareOptionsForSolver at 31
In fminunc at 157
Warning: Struct field assignment overwrites a value with class "double". See MATLAB R14SP2 Release
Notes, Assigning Nonstructure Variables As Structures Displays Warning, for details.
In fminunc at 203
Error using feval
Undefined function 'normal' for input arguments of type 'double'.
Error in fminunc (line 254)
f = feval(funfcn{3},x,varargin{:});
Caused by:
Failure in initial user-supplied objective function evaluation. FMINUNC cannot continue.
Unfortunately the manual did not help me to fix the code. Calling
[est, fval, exitflag, output, grad, hessian] = fminunc(f, x, theta)
did not help either. What am I doing wrong?
Thank you in advance!
You have called fminunc with the wrong sintax, please refer to the documentation.
A way to fix your code is by defining the function normal to accept only one parameter: theta.
function f = normal(theta)
global X
mean = theta(1);
sigma = theta(2);
z = (X-mean)./sigma;
f = -(sum(-log(sigma) -(1/2).*z.^2 ));
and call fminunc with
global X
X = randn(100, 1); % A possible time series.
theta0 = [1,1];
[est, fval, exitflag, output, grad, hessian] = fminunc(#normal, theta0);