How to initialize optional struct/class input variables in the "arguments" block?

14 次查看(过去 30 天)
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
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 个)

类别

Help CenterFile Exchange 中查找有关 Automotive 的更多信息

产品


版本

R2022b

Community Treasure Hunt

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

Start Hunting!

Translated by