VertConcatenated Parsing of Respective Function Outputs

1 次查看(过去 30 天)
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;

回答(1 个)

Guillaume
Guillaume 2014-9-21
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 个评论
Guillaume
Guillaume 2014-9-22
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
Guillaume 2014-9-22
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

请先登录,再进行评论。

类别

Help CenterFile Exchange 中查找有关 Surrogate Optimization 的更多信息

产品

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by