You are now following this question
- You will see updates in your followed content feed.
- You may receive emails, depending on your communication preferences.
Error using fzero " FUN must be a function, a valid string expression, or an inline function object"
27 views (last 30 days)
Show older comments
I am getting errors while using fsolve or fzero in the following code:
U = 1;
while U < 20
eq = @(q) 2.*(1-cos(2.*pi.*q));
hq = @(q,n0) ((eq(q)).^2+2.*U.*n0.*(eq(q))).^0.5;
y = @(q,n0) (((eq(q))+(U.*n0))./hq(q,n0))-1;
a = -0.5;
c = -0.01;
v = @(n0) (integral(@(q) y(q,n0),a,c));
cv =@(n0) n0+(0.5*v(n0))-1;
n0 = fzero(cv(n0),0.1);
plot(U,n0)
hold on
U = U + 1;
end
Can anyone please help me out?
Accepted Answer
Matt J
on 25 Feb 2015
n0 = fzero(cv,0.1);
4 Comments
jayash
on 25 Feb 2015
Sorry for novice queries. I corrected the code, but still I am not getting the plot (Its blank) its says
U = 1;
while U < 20
eq = @(q) 2.*(1-cos(2.*pi.*q));
hq = @(q,n0) ((eq(q)).^2+2.*U.*n0.*(eq(q))).^0.5;
y = @(q,n0) (((eq(q))+(U.*n0))./hq(q,n0))-1;
a = -0.5;
c = -0.1;
b = 0.1;
d = 0.5;
v = @(n0) (quad(@(q) y(q,n0),a,c) + quad(@(q) y(q,n0),b,d));
cv =@(n0) n0+(0.5*v(n0));
n = fzero(cv,0.1);
plot(U,n)
hold on
U = U + 1;
end
these warnings,
Exiting fzero: aborting search for an interval containing a sign change because complex function value encountered during search. (Function value at -0.028 is -0.056936-0.047268i.) Check function or try again with a different starting value.
More Answers (1)
John D'Errico
on 25 Feb 2015
Edited: John D'Errico
on 25 Feb 2015
cv is a function handle, i.e., perfectly valid for fzero to work on. It is a function that takes one argument, and returns an output that can be minimized.
cv(n0) is a variable. A number. Well, it would be, if n0 was defined. It may be so in your workspace, as otherwise, you would have gotten a different error before fzero was even entered.
Regardless, cv(n0) is NOT one of the valid things fzero can minimize.
There IS a difference. While you may THINK of cv as being a function of n0, when MATLAB sees the expression cv(n0), it looks around and says to itself, yep, I found n0. I found cv. It will evaluate that expression, then pass it in as an argument to a function called fzero.
Only then does fzero take control. It sees what was passed in, in this case, the variable that contains the result of cv(n0), where again, n0 MUST have been defined in your workspace, else you would have gotten a different error. That value is indeed NOT a function. Just a number. So fzero gets upset and tells you:
" FUN must be a function, a valid string expression, or an inline function object"
So the solution is simple. Remove the (n0) in your calls to fzero or to fsolve, like this:
n0 = fzero(cv,0.1);
19 Comments
INFOZOU
on 12 Aug 2017
I have the same error for the following code:
obj1 = zeros(c,1,f,t); % Allocate arrays
obj2 = zeros(c,2,f,t);
obj3 = zeros(u,c,f,t);
obj4 = zeros(u,j,t);
obj5 = zeros(u,f,t);
for nn=1:c
for ii=1:f
for jj=1:t
obj1(nn,1,ii,jj) = R(nn,1,ii)*Qr(nn,1,ii,jj);
end
end
end
for nn=1:c
for ii=1:f
for jj=1:t
obj2(nn,2,ii,jj) = R(nn,2,ii)*Qr(nn,2,ii,jj);
end
end
end
for ll=1:u
for nn=1:c
for ii=1:f
for jj=1:t
obj3(ll,nn,ii,jj) = CP(ll,ii)*QA(ll,nn,ii,jj);
end
end
end
end
for ll=1:u
for kk=1:j
for jj=1:t
obj4(ll,kk,jj) = CC(kk)*Ratp(ll,kk,jj);
end
end
end
for ll=1:u
for ii=1:f
for jj=1:t
obj5(ll,ii,jj) = CP(ll,ii)*QP(ll,ii,jj);
end
end
end
obj = [obj1(:);obj2(:);obj3(:);obj4(:);obj5(:)];
.......................
opts = optimoptions(@fmincon,'Algorithm','interior-point','Display','off');
[solution,fval,exitflag,output,lambda,grad,hessian] = fmincon(obj,zeros(size(obj)),Aineq,bineq,Aeq,beq,[],[],@fminconstr,opts)
Please, could you help me to solve this error:
"Error using optimfcnchk (line 101)
FUN must be a function, a valid character vector expression, or an inline function object.
Error in fmincon (line 399)
funfcn = optimfcnchk(FUN,'fmincon',length(varargin),funValCheck,flags.grad,flags.hess,false,Algorithm);
Error in asmaMODEL2 (line 289)
[solution,fval,exitflag,output,lambda,grad,hessian] = fmincon(obj,zeros(size(obj)),Aineq,bineq,Aeq,beq,[],[],@fminconstr,opts)
"
Matt J
on 12 Aug 2017
Lilia,
It does not make sense to pass numeric quantities like 'obj' to fmincon. If you are trying to find the minimum of a numeric array, just do
min(obj(:))
INFOZOU
on 12 Aug 2017
It is an objective function based on matrixes with linear constraints of equalities and inequalities and with non linear constraints.

Matt J
on 12 Aug 2017
The code you've shown indicates that obj is a numeric array. FMINCON does not accept numeric arrays as its first input. As the documentation for fmincon will tell you, the first input must be a function handle.
Walter Roberson
on 12 Aug 2017
If it is an objective function, then what is its "free variable" (or variables) that you are optimizing over?
INFOZOU
on 13 Aug 2017
This is the all program:
clc;
clear all;
%rng(1) % for reproducibility
u=3; %factories
c=3; %centers
j=3; %composants
f=4; %products
k=2; %clients
t=3; %time
N2=u*u;
xyloc = randperm(N2,u+c+k); % unique locations of facilities
[xloc,yloc] = ind2sub([u u],xyloc);
h = figure;
plot(xloc(1:u),yloc(1:u),'rs',xloc(u+1:u+c),yloc(u+1:u+c),'k*',...
xloc(u+c+1:u+c+k),yloc(u+c+1:u+c+k),'bo');
lgnd = legend('Factories','Distribution centers','Clients','Location','EastOutside');
lgnd.AutoUpdate = 'off';
xlim([0 u+1]);ylim([0 u+1])
%atp = zeros(u,j,t)
atp(1,:,:)=[470 490 480; 450 470 500; 460 510 490];
atp(2,:,:)=[450 480 480; 460 490 510; 470 520 500];
atp(3,:,:)=[460 480 490; 460 490 500; 460 510 500];
ctp=[550 580 580; 570 550 580; 530 550 580];
p=[1 1.2 1.3 1.4];
a=[1 2 1; 1 1 1; 1 2 2; 1 1 2];
D(1,:,:)=[100 108 105; 110 120 120;110 110 105; 95 105 100];
D(2,:,:)=[102 107 107; 114 115 114; 114 110 107; 97 107 102];
D(3,:,:)=[103 105 108; 118 115 110; 115 110 110; 98 110 103];
DE(1,1,:,:)= [65 70 70; 70 75 75; 80 80 70; 55 60 65];
DE(1,2,:,:)=[35 40 35; 35 40 45; 30 30 30; 40 40 35];
DE(2,1,:,:)=[65 70 70; 75 80 75; 75 80 80; 55 65 60];
DE(2,2,:,:)=[35 35 35; 40 45 45; 35 30 30; 40 45 40];
DE(3,1,:,:)=[70 65 70; 75 60 55; 80 70 80; 60 75 70];
DE(3,2,:,:)=[35 40 40; 45 45 45; 40 40 30; 40 35 35];
R(1,:,:)=[150 187 260 216; 120 154 208 180];
R(2,:,:)=[165 204 280 234; 132 168 224 195];
R(3,:,:)=[160 175 210 185; 135 145 200 150];
CP=[10 11 12 10 ; 11 10 11 12; 12 10 10 10];
CS=[4 5 5 4; 5 4 5 4; 5 4 4 4];
CC=[2 3 2];
Tx=[0.6 0.4 0; 0.4 0.3 0.3; 0 0.3 0.7];
QP=zeros(u,f,t);
QA=zeros(u,c,f,t);
Qr=zeros(c,k,f,t);
pre_atp=zeros(u,c,j,t);
pre_ctp=zeros(u,c,t);
Ratp = zeros(u,j,t); % Allocate as sparse
pre_ctpc = zeros(c,k,t);
pre_atpc = zeros(c,k,j,t);
obj1 = zeros(c,1,f,t); % Allocate arrays
obj2 = zeros(c,2,f,t);
obj3 = zeros(u,c,f,t);
obj4 = zeros(u,j,t);
obj5 = zeros(u,f,t);
for nn=1:c
for ii=1:f
for jj=1:t
obj1(nn,1,ii,jj) = R(nn,1,ii)*Qr(nn,1,ii,jj);
end
end
end
for nn=1:c
for ii=1:f
for jj=1:t
obj2(nn,2,ii,jj) = R(nn,2,ii)*Qr(nn,2,ii,jj);
end
end
end
for ll=1:u
for nn=1:c
for ii=1:f
for jj=1:t
obj3(ll,nn,ii,jj) = CP(ll,ii)*QA(ll,nn,ii,jj);
end
end
end
end
for ll=1:u
for kk=1:j
for jj=1:t
obj4(ll,kk,jj) = CC(kk)*Ratp(ll,kk,jj);
end
end
end
for ll=1:u
for ii=1:f
for jj=1:t
obj5(ll,ii,jj) = CP(ll,ii)*QP(ll,ii,jj);
end
end
end
obj = [obj1(:);obj2(:);obj3(:);obj4(:);obj5(:)];
% obj is the objective function vector
%x0 = [-1,1]; % Make a starting guess at the solution
matwid=length(obj);
clearer1 = zeros(size(obj1));
clearer12 = clearer1(:);
clearer2 = zeros(size(obj2));
clearer22 = clearer2(:);
clearer3 = zeros(size(obj3));
clearer32 = clearer3(:);
clearer4 = zeros(size(obj4));
clearer42 = clearer4(:);
clearer5 = zeros(size(obj5));
clearer52 = clearer3(:);
Aineq=spalloc(u*j*t+u*t+u*f*t,matwid,u*f*j*t+u*f*t+u*f*t);
bineq=zeros(u*j*t+u*t+u*f*t,1);
counter=1;
for ll=1:u
for kk=1:j
for jj=1:t
xtemp = clearer5;
xtemp(ll,:,jj) = a(:,kk); % Sum over warehouses for each product and factory
xtemp = sparse([clearer12;clearer22;clearer32;clearer42;xtemp(:)]); % Convert to sparse
Aineq(counter,:) = xtemp'; % Fill in the row
bineq(counter) = atp(ll,kk,jj);
counter = counter + 1;
end
end
end
for ll=1:u
for jj=1:t
xtemp = clearer5;
xtemp(ll,:,jj) = p(1,:); % Sum over warehouses for each product and factory
xtemp = sparse([clearer12;clearer22;clearer32;clearer42;xtemp(:)]); % Convert to sparse
Aineq(counter,:) = xtemp'; % Fill in the row
bineq(counter) = ctp(ll,jj);
counter = counter + 1;
end
end
for ll=1:u
for ii=1:f
for jj=1:t
xtemp = clearer5;
xtemp(ll,ii,jj) = 1; % Sum over warehouses for each product and factory
xtemp = sparse([clearer12;clearer22;clearer32;clearer42;xtemp(:)]); % Convert to sparse
Aineq(counter,:) = xtemp'; % Fill in the row
bineq(counter) = D(ll,ii,jj);
counter = counter + 1;
end
end
end
Aeq=spalloc(u*c*f*t+u*f*t+u*j*t,matwid,3*u*c*f*t+u*f*t+u*f*j*t+u*j*t);
beq=zeros(u*c*f*t+u*f*t+u*j*t,1);
counter=1;
for ll=1:u
for nn=1:c
for ii=1:f
for jj=1:t
xtemp = clearer3;
xtemp(ll,nn,ii,jj) = 1;
xtemp2=clearer5;
xtemp2(ll,ii,jj) = -Tx(ll,nn);
xtemp = sparse([clearer12;clearer22;xtemp(:);clearer42;xtemp2(:)]'); % Convert to sparse
Aeq(counter,:) = xtemp; % Fill in the row
counter = counter + 1;
end
end
end
end
for ll=1:u
for ii=1:f
for jj=1:t
xtemp = clearer3;
xtemp(ll,:,ii,jj) = -1;
xtemp2=clearer5;
xtemp2(ll,ii,jj) = 1;
xtemp = sparse([clearer12;clearer22;xtemp(:);clearer42;xtemp2(:)]'); % Convert to sparse
Aeq(counter,:) = xtemp; % Fill in the row
counter = counter + 1;
end
end
end
for ll=1:u
% for nn=1:c
%for ii=1:f
for kk=1:j
for jj=1:t
xtemp = clearer4;
xtemp(ll,kk,jj) = 1;
xtemp2=clearer5;
xtemp2(ll,:,jj) = a(:,kk);
xtemp = sparse([clearer12;clearer22;clearer32;xtemp(:);xtemp2(:)]'); % Convert to sparse
Aeq(counter,:) = xtemp; % Fill in the row
beq(counter) = atp(ll,kk,jj);
counter = counter + 1;
end
end
end
opts = optimoptions(@fmincon,'Algorithm','interior-point','Display','off');
[solution,fval,exitflag,output,lambda,grad,hessian] = fmincon(obj,zeros(size(obj)),Aineq,bineq,Aeq,beq,[],[],@fminconstr,opts)
exitflag
% infeas1 = max(Aineq*solution - bineq)
% infeas2 = norm(Aeq*solution - beq,Inf)
% diffint = norm(solution(intcon) - round(solution(intcon)),Inf)
% solution(intcon) = round(solution(intcon));
for ll=1:u
for nn=1:c
for ii=1:f
for kk=1:j
for jj=1:t
Rctp(ll,jj)=ctp(ll,jj)-sum(QP(ll,:,jj)*p(ii));
pre_atp(ll,nn,kk,jj)=sum(QA(ll,nn,:,jj)*a(:,kk));
pre_ctp(ll,nn,jj)=sum(QA(ll,nn,:,jj)*p(:));
end
end
end
end
end
for ll=1:u
for nn=1:c
for ii=1:f
for kk=1:j
for jj=1:t
for mm=1:k
pre_atpc(nn,mm,kk,jj)=Qr(nn,mm,ii,jj)*a(ii,kk);
pre_ctpc(nn,mm,jj)=p(ii)*Qr(nn,mm,ii,jj);
end
end
end
end
end
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
The non linear constraints are programmed in the following function fminconstr.m
function [c,ceq] = fminconstr()
u=3; %factories
c=3; %centers
j=3; %composants
f=4; %products
k=2; %clients
t=3; %time
%DE=120*rand(c,k,f,t)+30;
DE(1,1,:,:)= [65 70 70; 70 75 75; 80 80 70; 55 60 65];
DE(1,2,:,:)=[35 40 35; 35 40 45; 30 30 30; 40 40 35];
DE(2,1,:,:)=[65 70 70; 75 80 75; 75 80 80; 55 65 60];
DE(2,2,:,:)=[35 35 35; 40 45 45; 35 30 30; 40 45 40];
DE(3,1,:,:)=[70 65 70; 75 60 55; 80 70 80; 60 75 70];
DE(3,2,:,:)=[35 40 40; 45 45 45; 40 40 30; 40 35 35];
Qr=zeros(c,k,f,t);
for ll=1:u
for nn=1:c
for ii=1:f
for kk=1:j
for jj=1:t
if DE(nn,1,ii,jj)>sum(QA(:,nn,ii,jj))
X(nn,1,ii,jj)=1;
Y(nn,1,ii,jj)=1-X(nn,1,ii,jj);
Qr(nn,1,ii,jj)=sum(QA(:,nn,ii,jj))*X(nn,1,ii,jj)+DE(nn,1,ii,jj)* Y(nn,1,ii,jj);
else
X(nn,1,ii,jj)=0;
Y(nn,1,ii,jj)=1-X(nn,1,ii,jj);
Qr(nn,1,ii,jj)=sum(QA(:,nn,ii,jj))*X(nn,1,ii,jj)+DE(nn,1,ii,jj)* Y(nn,1,ii,jj);
end
if DE(nn,2,ii,jj)>sum(QA(:,nn,ii,jj))
Z(nn,2,ii,jj)=1;
Y(nn,2,ii,jj)=1-Z(nn,2,ii,jj);
Qr(nn,2,ii,jj)=(sum(QA(:,nn,ii,jj))-Qr(nn,1,ii,jj))*Z(nn,2,ii,jj)+DE(nn,2,ii,jj)* Y(nn,2,ii,jj);
else
Z(nn,2,ii,jj)=0;
Y(nn,2,ii,jj)=1-Z(nn,2,ii,jj);
Qr(nn,2,ii,jj)=(sum(QA(:,nn,ii,jj))-Qr(nn,1,ii,jj))*Z(nn,2,ii,jj)+DE(nn,2,ii,jj)* Y(nn,2,ii,jj);
end
end
end
end
end
end
c = []; % no nonlinear inequality
ceq = Qr; % the fsolve objective is fmincon constraints
Matt J
on 13 Aug 2017
Again, "obj" cannot be an objective function. It is just an array of numbers. The objective function must be expressed as a function handle, just as you have done with @fminconstr.
Walter Roberson
on 13 Aug 2017
You showed us a formula involving a number of summations with apparently known bounds such as C. Which variables in the overall expression are the ones which are to be "tuned" in order to optimize the result?
INFOZOU
on 13 Aug 2017
We should optimize the following 5 matrices :
Qr(c,1,f,t) Qr(c,2,f,t) QA(u,c,f,t) Ratp(u,j,t) QP(u,f,t)
Matt J
on 13 Aug 2017
What does it mean to optimize the matrices? What function are you minimizing to make them "optimal"?
Walter Roberson
on 13 Aug 2017
Could you confirm that what you mean is that the values of the matrices Qr, QA, Rapt, and QP, should be changed to try to find the minimum value of the function? So the output should be the combination of Qr, QA, Rapt, and QP that together produced the optimum value?
... because if so, then a glance at the formula suggests that the optimal values would be a mix of positive and negative infinities, with the signs of each depending on the signs of the other terms.
INFOZOU
on 13 Aug 2017
Please find the attached file containing the objective function with all constraints.
I know that I should use function with fmincon but I don't know how solve this optimization problem containing many matrices and variables.
That's why, I am refered to this example: https://www.mathworks.com/help/optim/examples/factory-warehouse-sales-allocation-model.html
INFOZOU
on 13 Aug 2017
@ Walter Roberson : Yes, I mean that the values of the matrices Qr, QA, Rapt, and QP, should be changed to try to find the maximum value of the function
Walter Roberson
on 13 Aug 2017
The approach you need to take is to construct a vector that is numel(Qr) + numel(QA) + numel(Rapt) + numel(QP) long, containing [Qr0(:); QA0(:); Rapt0(:); QP0(:)] where here the *0 indicates the initial value for the corresponding matrix.
You also need to express all of your linear constraints in terms of corresponding positions in that long vector.
Then you call fmincon() with the handle of an objective function, and the initial value vector, and the various constraint matrices.
Inside the objective function, you can do things like
Qr = reshape( X(17:52), 3, 2, 6 );
in order to extract from vector into variable names and shapes that are more understandable. And then you calculate the value of the objective function given those particular input values.
To emphasize: at the level of the fmincon() call, the matrices such as Qr and QA have no individual identity: everything has been spliced together into one continuous vector, which your objective function can then pull parts out of as needed.
You should be able to vectorize most of your multiplications using .* and then summing, or perhaps using * with appropriate transposes of the matrices to get the sizes to match. I see a couple of places in the formulas where you should be able to replace the multidimensional sum of A(I,J,K) x B(I,J,K,L) with sum(sum(sum(A.* sum(B,4),1),2,3) or something like that.
INFOZOU
on 15 Aug 2017
Thank you. In fact, the objective function "obj" is initially a vector (I have created a separated file containing the objective function attached in the objf.m file). I don't understand the need for using "numel" and "reshape" commands. I have now other problem with the function file: Error using objf Too many input arguments. Error in fmincon (line 536) initVals.f = feval(funfcn{3},X,varargin{:});
Error in MODEL2final (line 218) [solution,fval,exitflag,output,lambda,grad,hessian] = fmincon(@objf,zeros(size(obj')),Aineq,bineq,Aeq,beq,[],[],@fminconstr,Opt)
Caused by: Failure in initial objective function evaluation. FMINCON cannot continue.
Walter Roberson
on 16 Aug 2017
Well, I have attached altered files that at least allow the fmincon to run.
I am certain that you have coded your fminconstr incorrectly, but at least it runs. For example, your constraint on Qr should be an equality constraint, and instead of computing Qr, you should be computing the value and comparing it to Qr.
However, I could not do anything about your use of the undefined variable intcon . Note that fmincon is not for use with integer constraints -- or rather, if you want integer constraints then you need to code them as aspects of the non-linear constraints function, rejecting any values that are not integers (This will not be efficient.)
The minimization will run for a half hour or so -- I had to push the maximum function evaluations and the maximum iterations way up to get it to stop saying that it hadn't been given enough resources to finish. Now it finishes with
Converged to an infeasible point.
fmincon stopped because the size of the current step is less than the default value of the step size tolerance but constraints are not satisfied to within the selected value of the constraint tolerance.
exitflag = -2
fval = -4.66972258728847e+16
This is, I am sure, partly caused by you not having expressed your nonlinear constraints properly, but I can also see that it is headed for a negative infinity solution.
INFOZOU
on 20 Aug 2017
Hello
- I have changed the objfun=-sum(objvec) because I should to maximize this function
- I have added the lower bounds zeros(size(obj)) to obtain only positive results of X
- I have changed the Non linear constraints by the following expression: Qr(nn,1,ii,jj)=min(sum(QA(:,nn,ii,jj)),DE(nn,1,ii,jj)); Qr(nn,2,ii,jj)=min(sum(QA(:,nn,ii,jj))-Qr(nn,1,ii,jj),DE(nn,2,ii,jj));
- I want to verify if there are a difference in the constraints between: a*x<b and x*a<b and how I change the program for the second case.
I have obtained the following result: > In backsolveSys In solveKKTsystem In computeTrialStep In barrier In fmincon (line 798) In masterFINALMODEL2 (line 249) Warning: Matrix is close to singular or badly scaled. Results may be inaccurate. RCOND = 1.590792e-16.
Solver stopped prematurely.
fmincon stopped because it exceeded the function evaluation limit, options.MaxFunctionEvaluations = 1000000 (the selected value).
exitflag =
0
fval =
-1.1377e+23
I have tried using the optimisation tool also but there are the same problem and I have obtained the attached results.
<<

>>
Thank you very much for your cooperation
See Also
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!An Error Occurred
Unable to complete the action because of changes made to the page. Reload the page to see its updated state.
Select a Web Site
Choose a web site to get translated content where available and see local events and offers. Based on your location, we recommend that you select: .
You can also select a web site from the following list:
How to Get Best Site Performance
Select the China site (in Chinese or English) for best site performance. Other MathWorks country sites are not optimized for visits from your location.
Americas
- América Latina (Español)
- Canada (English)
- United States (English)
Europe
- Belgium (English)
- Denmark (English)
- Deutschland (Deutsch)
- España (Español)
- Finland (English)
- France (Français)
- Ireland (English)
- Italia (Italiano)
- Luxembourg (English)
- Netherlands (English)
- Norway (English)
- Österreich (Deutsch)
- Portugal (English)
- Sweden (English)
- Switzerland
- United Kingdom (English)
Asia Pacific
- Australia (English)
- India (English)
- New Zealand (English)
- 中国
- 日本Japanese (日本語)
- 한국Korean (한국어)