Skip to content
This repository was archived by the owner on Dec 10, 2021. It is now read-only.

Commit 9483597

Browse files
committed
Add "parseClassArgs"
Add "parseClassArgs" function, from WORMTRACK repo (rev e7b56ae).
1 parent ce9bf6f commit 9483597

File tree

1 file changed

+52
-0
lines changed

1 file changed

+52
-0
lines changed

parseClassArgs.m

Lines changed: 52 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,52 @@
1+
function parseClassArgs(args, obj)
2+
% Helper function for parsing args for class constructors.
3+
%
4+
% This is a variant of the 'parseArgs' function, and can be used to
5+
% automatically set object properties from a set of arguments passed into
6+
% a class constructor.
7+
%
8+
% Note that, in contrast to 'parseArgs', key names are case-sensitive. Also,
9+
% this function automatically detects whether an argument is a flag, by
10+
% reading the current value of the corresponding property: if this is a logical
11+
% scalar, the argument is assumed to be a flag.
12+
%
13+
% INPUT:
14+
% args = 'args' 1xN cell array
15+
% obj = object receiving property values
16+
17+
curArgIdx = 1;
18+
while curArgIdx <= length(args)
19+
if ischar(args{curArgIdx})
20+
if ~isprop(obj, args{curArgIdx})
21+
error('Invalid argument "%s": No property found with that name', args{curArgIdx});
22+
end
23+
24+
% Identify flag arguments by the data type of their
25+
% corresponding property:
26+
if islogical(obj.(args{curArgIdx})) && isscalar(obj.(args{curArgIdx}))
27+
if (curArgIdx+1) <= length(args) && islogical(args{curArgIdx+1}) && isscalar(args{curArgIdx+1})
28+
% Value is given explicitly
29+
obj.(args{curArgIdx}) = args{curArgIdx+1};
30+
curArgIdx = curArgIdx + 1;
31+
else
32+
% No value given, so turn the flag ON
33+
obj.(args{curArgIdx}) = true;
34+
end
35+
else
36+
% Non-flag properties: value should be given
37+
if (curArgIdx+1) <= length(args)
38+
obj.(args{curArgIdx}) = args{curArgIdx+1};
39+
curArgIdx = curArgIdx + 1;
40+
else
41+
error('Argument error: No value specified for argument "%s"', args{curArgIdx});
42+
end
43+
end
44+
else
45+
error('Invalid argument at position %d: String expected', curArgIdx);
46+
end
47+
48+
curArgIdx = curArgIdx + 1;
49+
end
50+
51+
end
52+

0 commit comments

Comments
 (0)