Output of a function as input of another function
5 vues (au cours des 30 derniers jours)
Afficher commentaires plus anciens
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 commentaires
Réponses (2)
Matt Fig
le 28 Oct 2012
Modifié(e) : Matt Fig
le 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 commentaires
Matt J
le 28 Oct 2012
Modifié(e) : Matt J
le 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 commentaires
Peanut
le 26 Mai 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
le 27 Mai 2020
Modifié(e) : Matt J
le 28 Mai 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)))
Voir également
Catégories
En savoir plus sur Assumptions dans Help Center et File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!