VertConcatenated Parsing of Respective Function Outputs
1 vue (au cours des 30 derniers jours)
Afficher commentaires plus anciens
Hi all I need a little help with syntax here, trying to vertically concatenate the respective outputs [c,ceq] from functions fcn1 and fcn2 below So [c,ceq] should be
c = [1;2;3;4] % concat of [1;2;] & [3;4]
ceq = [5;6] % concat of [] & [5;6]
For context, fcn will be a nonlinear constraint function for an fmincon, which can be comprised of potentially several fcn1,fcn2,fcn3.
all the best,
Mark
function [c,ceq] = TestFunctionDualOutputParsing
fcn = @(x) deal(fcn1(x),fcn2(x)); % doesn't work
[c,ceq] = fcn(1);
function [c1,ceq1] = fcn1(x)
c1 = [1;2].*x;
ceq1 = [].*x;
function [c2,ceq2] = fcn2(x)
c2 = [3;4].*x;
ceq2 = [5;6].*x;
0 commentaires
Réponses (1)
Guillaume
le 21 Sep 2014
Unfortunately, in matlab, there is no way to pass the second or later output of a function directly to another function. You have to use a temporary variable, which precludes doing it in an anonymous function. You don't have a choice but to implement it as a standard function:
function [c, ceq] = fcn(x)
[c1, ceq1] = fcn1(x);
[c2, ceq2] = fcn2(x);
c = [c1; c2];
ceq = [ceq1; ceq2];
end
3 commentaires
Guillaume
le 22 Sep 2014
Right, sorry I missed that you would have a varying number of function handles. The following will work:
function [out1, out2] = dispatch2output(x, varargin)
[out1, out2] = cellfun(@(fn) fn(x), varargin, 'uni', false);
out1 = vertcat(out1{:});
out2 = vertcat(out2{:});
end
You call it with:
[c, ceq] = dispatch2output(x, @fcn1);
[c, ceq] = dispatch2output(x, @fcn1, @fcn2);
[c, ceq] = dispatch2output(x, @fcn1, @fcn2, @fcn3);
Guillaume
le 22 Sep 2014
Finally, a generalisation of dispatch2output to any number of outputs:
function varargout = dispatchNoutput(x, varargin)
fnouts = cell(1, nargout);
[fnouts{:}] = cellfun(@(fn) fn(x), varargin, 'uni', false);
varargout = cellfun(@(c) vertcat(c{:}), fnouts, 'uni', false);
end
Voir également
Catégories
En savoir plus sur Surrogate Optimization dans Help Center et File Exchange
Produits
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!