How to handle functions with multiple outputs
조회 수: 36 (최근 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!