nargin of optional arugments
조회 수: 5 (최근 30일)
이전 댓글 표시
function func(arg1,options)
arguments
arg1 = 1
options.arg2 = 2
options.arg3 = 3
end
disp(nargin)
end
%%
func(1,arg2=3,arg3=5)
The function "func" has 3 input arguments, why nargin is 1? And how to get the number of all input arguments, including optional ones?
댓글 수: 2
Noé
2025년 2월 11일
Hi Wang,
As mentioned in https://mathworks.com/help/releases/R2024a/matlab/matlab_prog/nargin-in-argument-validation.html "The value that nargin returns does not include optional input arguments that are not included in the function call. Also, nargin does not count any name-value arguments."
Here arg2 and arg3 are optional arguments whereas arg1 is positional argument.
If you want to know how many arguments have been passed you can:
"Use nargin to determine if optional positional arguments are passed to the function when called. For example, this function declares three positional arguments and a name-value argument. Here is how the function determines what arguments are passed when it is called.
채택된 답변
Catalytic
2025년 2월 11일
편집: Catalytic
2025년 2월 11일
func(1,arg2=3,arg3=5)
function func(arg1,names,values)
arguments
arg1 = 1
end
arguments (Repeating)
names string
values double
end
NUM_ARGSIN = numel(names)+1
nvp=[names;values];
options=struct(nvp{:})
end
댓글 수: 2
Matt J
2025년 2월 11일
편집: Matt J
2025년 2월 11일
If you're going to look at it that way, I think it should be,
func()
func(10)
func(1,arg2=3,arg3=5)
function func(arg1,names,values)
arguments
arg1 = 1
end
arguments (Repeating)
names string
values double
end
NUM_ARGSIN = nargin - numel(names)
nvp=[names;values];
options=struct(nvp{:});
end
추가 답변 (1개)
Matt J
2025년 2월 11일
편집: Matt J
2025년 2월 11일
The function "func" has 3 input arguments, why nargin is 1?
There are 5 input arguments, not 3:
func(1,arg2=3,arg3=5)
function func(varargin)
NUM_ARGSIN = nargin
[arg1,options]=doValidations(varargin{:});
disp ' ', arg1, options
end
function [arg1,options]=doValidations(arg1,options)
arguments
arg1 = 1
options.arg2 = 2
options.arg3 = 3
end
end
댓글 수: 0
참고 항목
카테고리
Help Center 및 File Exchange에서 Search Path에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!