Function input argument block - defining multiple valid classes for input data.
25 views (last 30 days)
Show older comments
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 Comments
Accepted Answer
Stephen23
on 2 Jul 2024
Moved: Stephen23
on 2 Jul 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
More Answers (0)
See Also
Categories
Find more on Loops and Conditional Statements in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!