Matlab mustBeA for Matlab < R2020b

Matlab mustBeA is one of the most frequently used features we used from Matlab R2020b and newer. mustBeA allows validating a function argument is one of multiple classes, instead of the single class coercion used by Matlab by default.

Simply create a file in the project directory “mustBeA.m”, or under private/mustBeA.m if it’s a Matlab package.

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{File,folder} call.


Example: myfun.m:

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

...

end