What are all the ways to use name-value arguments in MATLAB code?

5 views (last 30 days)
I want to accept name-value arguments in my matlab code. Also, some of the name-value arguments may be optional and may take default values specified by me.

Accepted Answer

Ayush
Ayush on 14 Jul 2023
Edited: Ayush on 14 Jul 2023
Hi @Nitu,
There are various ways for implementing name-value arguments.
Some of the ways are as follows:
  • options argument
function res = func(a, b, options)
arguments
a %constraints of a
b %constraints of b
options.c = 1 % default value
options.d = 1 % default value
end
disp(a);disp(b);disp(options.c);disp(options.d);
end
Now, user can use the following syntaxes:
func(1,2);
func(1,2,'c',4); % a=1 b=2 c=4 (default value) d=1 (default value)
func(1,2,'d',3); % a=1 b=2 c=1 (default value) d=3
func(1,2,'c',3,'d',5); % a=1 b=2 c=3 d=5
  • varargin
function res = func(a, b, varargin)
% access the arguments
for ind=1:2:numel(varargin)
name=varargin{ind};
val=varargin{ind+1};
% do operations on these name-value arguments
end
% for pre-defined name-value arguments
% you can use input parser aswell
inp = inputParser;
% adding parameters
addParameter(inp, 'argName1', defaultValue, validationFcn);
addParameter(inp, 'argName2', defaultValue, validationFcn);
addParameter(inp, 'argName3', defaultValue, validationFcn);
% parse the parameters
parse(inp, varargin{:});
% Access
arg1 = inp.Results.argName1;
arg2 = inp.Results.argName2;
end
Now, user syntaxes:
func(1, 2, 'a', 2); % name-value argument : a=2
func(1, 2, 'c', 3, 'd', 4); % name-value arguments : c=3 and d=4
So, these were some ways to implement (optional) name-value arguments.
Hope it helps!

More Answers (0)

Categories

Find more on Argument Definitions in Help Center and File Exchange

Products

Community Treasure Hunt

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

Start Hunting!