How to initialize optional struct/class input variables in the "arguments" block?
14 次查看(过去 30 天)
显示 更早的评论
MathWorks Support Team
2023-7-20
回答: MathWorks Support Team
2023-7-20
I defined a function in the following form
function [obj] = func(obj, aa, bb, cc, dd)
arguments
obj;
aa;
bb = 'bb';
cc = obj.c;
dd.dd1 = ones(obj.dd1);
dd.dd2 = 2;
end
end
where "dd" can be a struct/class type optional input variable. By executing the following command
obj = func(obj, aa, bb, cc, dd)
I ran into the following error.
Error using xxx func
Invalid argument at position 5. Function requires 2 to 4 positional input(s).
How can I fix the error?
采纳的回答
MathWorks Support Team
2023-7-20
The abovementioned error was caused by the invalid use of the “arguments” block (i.e., declare validation argument validation). To properly define “dd” where the fields “dd1” and “dd2” are initialized with the default values, please refer to the updated example of “func” as shown below.
function [obj] = func(obj, aa, bb, cc, dd)
arguments
obj;
aa;
bb = 'bb';
cc = obj.c;
dd = struct('dd1', ones(obj.dd1), 'dd2', 2);
end
end
In the event where no optional argument “dd” is passed into “func” as shown in the example below
obj = func(obj, aa)
“dd” will be initialized by the default value “dd = struct('dd1', ones(obj.dd1), 'dd2', 2).” This is in agreement with the format of the “arguments” block as shown below.
arguments
argName1 (dimensions) class {validators} = defaultValue ...
argNameN ...
end
If you elect to pass “dd” when calling the function, the passed variable's value will be used instead of the default value initialized within the "arguments" block.
For more information and examples of the “arguments” block (i.e., declare validation argument validation), please refer to the documentation below:
0 个评论
更多回答(0 个)
另请参阅
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!