Function input argument block - defining multiple valid classes for input data.

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

采纳的回答

Stephen23
Stephen23 2024-7-2,20:29
移动:Stephen23 2024-7-2,20:35
"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!
Error using solution>DateTimeCheck (line 7)
Invalid argument at position 1. Input must be either a text input or datetime.
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
  1 个评论
John
John 2024-7-3,11:58
Thank you so much, I had already nested functions but got the error "Calling nested functions is not supported in arguments block." I didn't realize local functions were a thing/different than nested functions. Thanks and have a good day

请先登录,再进行评论。

更多回答(0 个)

类别

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

产品


版本

R2020b

Community Treasure Hunt

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

Start Hunting!

Translated by