How to handle functions with multiple outputs
Show older comments
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
Accepted Answer
More Answers (1)
madhan ravi
on 27 Jun 2020
[~, f2] = multfunc(x1, x2)
4 Comments
Samuel
on 27 Jun 2020
Walter Roberson
on 27 Jun 2020
you will need to use a real function to assign the result of multfunc to variables and then return f2 so it can be optimized.
In MATLAB it is not possible to capture the second or later output of a function within an expression: you need a true assignment statement and that requires a true function not an anonymous function.
Walter Roberson
on 27 Jun 2020
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.
Categories
Find more on Introduction to Installation and Licensing in Help Center and File Exchange
Products
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!