VertConcatenated Parsing of Respective Function Outputs

조회 수: 4 (최근 30일)
Mark Whirdy 2014년 9월 21일
댓글: Guillaume 2014년 9월 22일
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 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이전 댓글 1개 표시이전 댓글 1개 숨기기
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 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에서 Bartlett에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by