Parsing default function arguments: why isn't it better???
조회 수: 3 (최근 30일)
이전 댓글 표시
Hi all,
in octave, if i have a function fff where the 3rd argument is optional, i can give it a default value by doing
function fff(argv1, argv2, opt1=3)
This seems not to work in matlab. Thus i have to do sth like:
function fff(arg1,arg2,opt1)
if nargin < 3
opt1 = 3
end
and now the question: why??? Adding so many unnecessary lines! This seems like the worst syntax option possible. Can it get any better? I really appreciate your answer since i did not use matlab that often yet!
thx oxy
답변 (3개)
Azzi Abdelmalek
2014년 3월 18일
You have described a simple case, what if the situation is more complicated?
댓글 수: 0
David Young
2014년 3월 18일
The main tool MATLAB offers to handle optional arguments would look like this in your example:
function fff(arg1,arg2,varargin)
inp = inputParser;
inp.addOptional('opt1', 3);
inp.parse(varargin{:});
opt1 = inp.Results.opt1;
So although your own solution seems long and cumbersome to you, there is an even longer and more cumbersome way to do it available. As this suggests, your solution is about as neat as it gets provided you don't want validation - MATLAB simply does not include the syntax you show for Octave.
There are some contributions on the FEX that provide a neater-looking setup than the inputParser approach, and it might be worth looking into those - but it will still require code in the body of your function.
댓글 수: 0
참고 항목
카테고리
Help Center 및 File Exchange에서 Argument Definitions에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!