How to initialize optional struct/class input variables in the "arguments" block?
15 visualizaciones (últimos 30 días)
Mostrar comentarios más antiguos
MathWorks Support Team
el 20 de Jul. de 2023
Respondida: MathWorks Support Team
el 20 de Jul. de 2023
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?
Respuesta aceptada
MathWorks Support Team
el 20 de Jul. de 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:
0 comentarios
Más respuestas (0)
Ver también
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!