Matlab mustBeA for Matlab < R2020b

Matlab mustBeA is used in function argument validation to check that a variable is in one of multiple classes, instead of the single class coercion used by Matlab arguments block by default.

Simply create a file in the project directory “mustBeA.m”, or under private/mustBeA.m

function mustBeA(x, classes)
% for Matlab < R2020b
arguments
  x
  classes (1,:) string
end

mustBeMember(class(x), classes)

end

Matlab mustBeFile and mustBeFolder can fail to validate when the filename starts with a tilde “~”. Tilde is used by most terminal shells to indicate the user home directory. However, Matlab does not currently recognize tilde.

Workaround this issue with expanduser.m in the mustBe* call.


Example: myfun.m:

function myfun(A, B)
arguments
  A {mustBeA(A, ["string", "char"])}
  B (1,1) {mustBeNumeric}
end

...

end