Best practice for passing multiple shared parameters with flow through
조회 수: 17 (최근 30일)
이전 댓글 표시
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
Jeff Miller
2022년 6월 24일
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).
답변 (0개)
참고 항목
카테고리
Help Center 및 File Exchange에서 Creating, Deleting, and Querying Graphics Objects에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!