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

15 Ansichten (letzte 30 Tage)
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?

Akzeptierte Antwort

MathWorks Support Team
MathWorks Support Team am 20 Jul. 2023
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:

Weitere Antworten (0)

Kategorien

Mehr zu Automotive finden Sie in Help Center und File Exchange

Produkte


Version

R2022b

Community Treasure Hunt

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

Start Hunting!

Translated by