필터 지우기
필터 지우기

Error using fmincon with nested function.

조회 수: 2 (최근 30일)
wei zhang
wei zhang 2016년 8월 24일
댓글: Walter Roberson 2016년 8월 24일
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.

답변 (1개)

Walter Roberson
Walter Roberson 2016년 8월 24일
[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
wei zhang
wei zhang 2016년 8월 24일
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 2016년 8월 24일
Please Accept the solution if it works for you.

댓글을 달려면 로그인하십시오.

카테고리

Help CenterFile Exchange에서 App Building에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by