Error using fmincon with nested function.

3 vues (au cours des 30 derniers jours)
wei zhang
wei zhang le 24 Août 2016
Commenté : Walter Roberson le 24 Août 2016
First I have a nested function test1 calling test0 as described following,
function y = test0(x)
y=x^2
end
function y=test1(x)
y=x(1)+x(2)+test0(x(1));
end
Next I use the fmincon to calculate the mininum of the function.
X0=[0.1;0.1];
LB=[0;0.71];
UB=[2;6.53];
[result,FVAL,EXITFLAG]=fmincon(test1,X0,[],[],[],[],LB,UB)
Then error as following,
Not enough input arguments.
Error in test1 (line 2)
y=x(1)+x(2)+test0(x(1));;
Error in calculate (line 4)
result,FVAL,EXITFLAG]=fmincon(test1,X0,[],[],[],[],LB,UB)
I give the test0 and test1 function as examples. For the complexity of the function, I cannot write the whole function in one step. Please help me, maybe give some way to write the function more expediently? Thank you very much.

Réponses (1)

Walter Roberson
Walter Roberson le 24 Août 2016
[result,FVAL,EXITFLAG]=fmincon(test1,X0,[],[],[],[],LB,UB)
means to call test1 with no arguments and to use the result (which would have to be a function handle or string) as the function to minimize over. Try
[result,FVAL,EXITFLAG]=fmincon(@test1,X0,[],[],[],[],LB,UB)
Your code does not use nested functions, it uses a script, and two functions defined with static workspaces. We cannot tell which file test1 is defined in: if it is not in test1.m then you would not be able to obtain a function handle to it from outside whatever file it is in. If test0 and test1 are both in test0.m then you would need to take extra steps to have test0 return the function handle to test1 . For example,
function y = test0(x)
if nargin == 0
y = @test1;
else
y = x.^2;
end
function y = test1(x)
y = x(1) + x(2) + test0(x(1));
end
and
X0=[0.1;0.1];
LB=[0;0.71];
UB=[2;6.53];
fun = test0(); %get handle to real function
[result, FVAL, EXITFLAG] = fmincon(fun, X0, [], [], [], [], LB, UB);
  2 commentaires
wei zhang
wei zhang le 24 Août 2016
Thank you for your answer. Added the symbol @, the code works well now! I define the test0 and test1 in different function scripts now. Thank you for your advice again!
Walter Roberson
Walter Roberson le 24 Août 2016
Please Accept the solution if it works for you.

Connectez-vous pour commenter.

Catégories

En savoir plus sur Argument Definitions dans Help Center et File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by