Function input argument block - defining multiple valid classes for input data.
32 visualizaciones (últimos 30 días)
Mostrar comentarios más antiguos
John
el 2 de Jul. de 2024
Comentada: John
el 3 de Jul. de 2024
Hello,
I am attempting to create a function which will accept multiple different object classes as input. I want to accept: char, string, and datetime using the arguments block. Currently I only have it accepting the input data as char and string, for example:
function [datetimeout, datetimeopt, errortype] = DateTimeCheck(data, type, output)
arguments
data {mustBeText}
type {mustBeText}
output {mustBeText} = 'datetime'
end
%rest of the function%%
end
I was able to find a workaround by creating and calling another function. In the main function the syntax would be as follows:
function [datetimeout, datetimeopt, errortype] = DateTimeCheck(data, type, output)
arguments
data {mustbedatetimecheck}
type {mustBeText}
output {mustBeText} = 'datetime'
end
%%rest of the function%%
end
Then in the second function:
function mustbedatetimecheck(a)
if ~(isa(a,'datetime') || isa(a,'char') || isa(a, 'string'))
eidType = 'mustbedatetimecheck:nottextordatetime';
msgType = 'Input must be either a text input or datetime.';
error(eidType,msgType)
end
end
I'd like to consolidate these two functions into one function so I do not have the need for multiple files. I understand it's possible to complete this using isa statements after the arguments block, however this is not as concice as having the statement within the arguments block.
Thank you in advance for your time and help.
0 comentarios
Respuesta aceptada
Stephen23
el 2 de Jul. de 2024
Movida: Stephen23
el 2 de Jul. de 2024
"I'd like to consolidate these two functions into one function so I do not have the need for multiple files."
You do not need multiple files: simply define mustbedatetimecheck as a local function in the same file:
DateTimeCheck(datetime('now'), 'hello','world') % ok
DateTimeCheck("String input", 'hello','world') % ok
DateTimeCheck(cell(1,2), 'hello','world') % error!
function DateTimeCheck(data, type, output)
arguments
data {mustbedatetimecheck}
type {mustBeText}
output {mustBeText} = 'datetime'
end
%%rest of the function%%
end
function mustbedatetimecheck(a)
assert(isa(a,'datetime') || isa(a,'char') || isa(a,'string'),...
'mustbedatetimecheck:nottextordatetime',...
'Input must be either a text input or datetime.')
end
Más respuestas (0)
Ver también
Categorías
Más información sobre Loops and Conditional Statements en Help Center y File Exchange.
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!