Does any elegant way to pass augments through nested function calls

2 views (last 30 days)
Hello,
I encountered some case of code which written like follows.
The problem is the augments are difficult to handle if these are named lengthy.
My question is does any ways keep the function structure but easier to handle and debug?
script.m
b = 1;
c = 2;
d = 3;
e = 4;
f = 5;
g = 6;
h = 7;
i = 8;
j = 9;
k = 'nest';
a = nestb(b,c,d,e,f,g,h,i,j,k)
nestb.m
function varargout = nestb(varargin)
b = varargin{1}
c = varargin{2}
d = varargin{3}
e = varargin{4}
f = varargin{5}
g = varargin{6}
h = varargin{7}
i = varargin{8}
j = varargin{9}
k = varargin{10}
if numel{varargin} > 10
test = varargin{11}
qq = varargin{12}
ww = varargin{13}
end
if b > 0
tmpb = b + nestc(c,d,e,f)
else
tmpb = nestc(c,d,e,f)
end
varargout{1} = tmpb;
end
nestc.m
function varargout = nestc(varargin)
c = varargin{1}
d = varargin{2}
e = varargin{3}
f = varargin{4}
g = varargin{5}
h = varargin{6}
i = varargin{7}
j = varargin{8}
k = varargin{9}
if c > 0
tmpc = c + nestd(d,e,f,g,h,i,j,k)
else
tmpc = nestd(d,e,f,g,h,i,j,k)
end
varargout{1} = tmpc;
end
nestd.m
function varargout = nestd(varargin)
d = varargin{1}
e = varargin{2}
f = varargin{3}
g = varargin{4}
h = varargin{5}
i = varargin{6}
j = varargin{7}
k = varargin{8}
if isnumeric(k)
tmpd = d + e + f + g + h + i + j + k;
else
tmpc = d + e + f + g + h + i + j;
end
varargout{1} = tmpd;
end

Accepted Answer

Adam Danz
Adam Danz on 9 Feb 2019
Instead of using vargin, you could include one input that is either a cell array or a structure.
Example using cell array
allInputs = {1,2,3,4,5,6,7,8,9,'nest',[],[],[]}
a = nestb(allInputs)
function varargout = nestb(allInputs)
% b will always be allInputs{1}
% k will always be allInputs{11} (and it might be empty)
% to determine which inputs are not empty: ~cellfun(@isempty, allInputs)
if allInputs{1} > 0
tmpb = allInputs{1} + nestc(allInputs{2:5})
else
tmpb = nestc(allInputs{2:5})
end
varargout{1} = tmpb;
end
Example using structure
allInputs.b = 1;
allInputs.c = 2;
allInputs.d = 3; %etc...
allInputs.k = 'nest';
a = nestb(allInputs)
function varargout = nestb(allInputs)
% test will always be allInputs{11} and it might be empty
% to determine if a field exists: isfield(allInputs, 'fieldname')
if allInputs.b > 0
tmpb = allInputs.b + nestc(allInputs) %adapt nestc() to handle structure input
else
tmpb = nestc(allInputs)
end
varargout{1} = tmpb;
end

More Answers (0)

Categories

Find more on Variables 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!