Output of a function as input of another function
5 views (last 30 days)
Show older comments
Suppose, I have a function which gives me two matrices A and B as output and I want to use these 2 matrices as inputs for another function, how do I do it? I don't want to copy paste the output matrices or type the entire matrices as input for the second function.
0 Comments
Answers (2)
Matt Fig
on 28 Oct 2012
Edited: Matt Fig
on 28 Oct 2012
Say your first function is named FUNC1, and your second function is named FUNC2. You do not specify if FUNC2 returns any value...
[A,B] = func1(args);
func2(A,B);
A real life example that you can copy/paste!
[I,J] = max(magic(5)) % Call the MAX function with two returns.
power(I,J) % Pass return args from MAX to POWER. (I.^J)
0 Comments
Matt J
on 28 Oct 2012
Edited: Matt J
on 28 Oct 2012
If you mean you'd like to call func2(func1) in a single statement, then don't return A and B as separate output arguments from your first function. Have your first function pack them in a cell array. I.e., instead of
function [A,B]=func1(n)
A=rand(n);B=rand(n,2);
function C=func2(A,B)
C=A*B;
you could instead do this
function AB=func1(n)
AB={rand(n); rand(n,2)};
function C=func2(AB)
C=AB{1}*AB{2};
And now you can do
C=func2(func1(n));
4 Comments
Peanut
on 26 May 2020
As I mentioned before, I can't change func2 (as it's a matlab function). I'll clarify exactly what the situation is:
syms x y z
eq1 = x == y^2
eq2 = y == z-1
eq2C = num2cell(children(eq2))
subs(eq1,eq2C{:})
Ideally, eq2C is never created. Something like below:
syms x y z
eq1 = x == y^2
eq2 = y == z-1
subs(eq1,num2cell(children(eq2)){:})
Matt J
on 27 May 2020
Edited: Matt J
on 28 May 2020
You're viewing subs as playing the role of func2 here. I can see why you can't modify subs directly, but I don't see why you couldn't write a wrapper for subs that will do the expansion for you:
function out=mysubs(eq,argCell)
out=subs(eq,argCell{:});
end
and apply it to your example as follows
syms x y z
eq1 = x == y^2
eq2 = y == z-1
mysubs(eq1,num2cell(children(eq2)))
To make something generally applicable beyond just subs(), you could write a general utility function called, say, myfeval
function varargout=myfeval(fun,varargin)
[varargout{1:nargout}]=feval(fun,varargin{1:end-1},varargin{end}{:});
end
and apply it to your example as,
syms x y z
eq1 = x == y^2
eq2 = y == z-1
myfeval(@subs,eq1,num2cell(children(eq2)))
See Also
Categories
Find more on Assumptions in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!