How to handle functions with multiple outputs
218 次查看(过去 30 天)
显示 更早的评论
Dear matlab users,
I have a function with multiple returns, and I want to handle the single output as anonymous function.Let me explain it a bit more,I have afunction multfunc with outputs f1,and f2 as described below
function [f1,f2]=multfunc(x1,x2)
f1=x1*log(x2);
f2=x2^2;
end
I want to find the extremem of f2 and I gave a try as follws:
[~,f2]=@(x1,x2)multfunc(x1,x2)
then in the error is:Only functions can return multiple values
my intention is to return both functions and want to handle f2,How could I do that?
Thanks
0 个评论
采纳的回答
Rik
2020-6-27
You will need a wrapper function (which you can make fancy if you want, but I made it simple).
f=@(x1,x2)wrapper(x1,x2);
function y=wrapper(x1, x2)
[~,y]=multfunc(x1,x2)
end
4 个评论
Rik
2020-6-27
If you leave multfunc intact you can very easily get the value of f1 for a minimized f2:
f=@(x)wrapper(x(1),x(2));
x = fminsearch(f,[10,10])
f1=multfunc(x(1),x(2));
What is your actual goal? You seem to be changing the code I'm suggestion for no obvious reason.
更多回答(1 个)
madhan ravi
2020-6-27
[~, f2] = multfunc(x1, x2)
4 个评论
Walter Roberson
2020-6-27
function v = Out2(f, varargin)
[v{1}, v{2}] = f(varargin{:});
Now instead of calling multfunc(x1, x2) instead call Out2(@multfunc, x1, x2)
What you get back will be a cell array with the two outputs. You can then extract the entries from the cell array.
What you cannot do at all easily is use something like ga or fmincon to optimize the second value and then at the end have the optimization routine return the optimal x1 x2 and the optimal value for f2 and simultaneously the f1 corresponding to the optimal f2. The optimization routines are not able to handle output to optimize over along with "extra values".
If that is what you want to do, find the f1 corresponding to the optimal f2, then the easiest way is to use a function similar to the above Out2 that returns only the f2 value, and optimize on that, and then once you know the location of the optimum, call multfunc with that location and look at both outputs. This does involve one "extra" call to multfunc, but it is by far the easiest way to code the situation.
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Introduction to Installation and Licensing 的更多信息
产品
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!