Best practice for passing multiple shared parameters with flow through

5 views (last 30 days)
This is somewhat of a general programming but specific to MATLAB. I have a bunch of functions which with a few exceptions consist of 1 required parameter and 1 or more 'Parameter', 'Value' pairs using varargin, inputParser, addRequired, and addParameter. As it happens, code balloons and now I'm having to deal with a lot of redundant code and inefficient debugging.
For example I have the function "fA" which takes vector/matrix v1 and outputs v2 with some default calculations, but I can override some of these with the parameters. Similarly I have function "fB" which does it with different parameters to go v2-->v3. So any of these will work:
fA(1:5)
fA([1 9; 4 5], 'Multiplier', 2)
fB([3 7 9])
fB([3 7 9], 'OutputAsInteger', true, 'Exponent', 1)
However, I also implement convenience wrapper fC which goes directly from v1-->v3. Before things got too complicated, I had it parse all 3 inputs, but for the most part pass them as provided or as default via varargin{:}. This then requires me to edit fA to accept the two other arguments and fB to accept 'Square'. I switched to using the parser's KeepUnmatched = true property and passing that result, which avoids crashes better but still is difficult to debug any changes.
So what's the best way to handle this across these 3 functions, and expand to dozens of similar functions? I think I could work up a general struct() object that passes to every single function and they only accept the values they need, but is this the best way?
  3 Comments
Sean O'Neil
Sean O'Neil on 24 Jun 2022
Hmm, maybe it's just that. I found your answer very helpful though as it confirmed that I check KeepUnmatched and it needs to be in every function so I'll have to go through and make sure it's always there. Or make another function that handles it for all for function brevity.
To clarify based on your example, I would want it like this:
y = function fC(data,varargin)
x = fA(data,varargin{:});
y = fB(x,varargin{:});
end
Where fB gets from fA not fC.
I think that sovled things but I'll try some more testing. Thank you.
Jeff Miller
Jeff Miller on 24 Jun 2022
Glad that was helpful. Just note that this approach is a little error-prone in that there is no warning or error if you call fC with an illegal argument (e.g., you mis-spell the name in one of the name/value pairs used by fA or fB).

Sign in to comment.

Answers (0)

Categories

Find more on Argument Definitions in Help Center and File Exchange

Products


Release

R2021b

Community Treasure Hunt

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

Start Hunting!