Error using fmincon with nested function.
3 次查看(过去 30 天)
显示 更早的评论
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.
0 个评论
回答(1 个)
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 个评论
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Argument Definitions 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!