How to handle functions with multiple outputs
34 ビュー (過去 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 で Surrogate Optimization についてさらに検索
製品
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!