Matlab builtin() function overload
Matlab built-in functions can be overloaded in classes or in general. This can be useful when making code compatible with both Matlab and GNU Octave, or to be compatible with older Matlab versions.
For example, the Matlab built-in function
strlength
gets the length of char
and string
arrays, but older Matlab and GNU Octave don’t have this function.
We made a function in strlength.m in a project’s private/ directory like:
%% STRLENGTH get length of character vector or scalar string
function L = strlength(s)
L = [];
if ischar(s)
L = length(s);
elseif isstring(s)
L = builtin('strlength', char(s));
% char() is workaround for bug described below
end
end
A bug we found and confirmed by Xinyue Xia of Mathworks Technical Support is as follows:
strlength()
works with char, or string scalars or N-D arrays.
However, when using
builtin('strlength')
only char is accepted. Scalar or N-D string array errors unexpectedly.
Example:
builtin('strlength', ["hi", "there"])
we expect to get [2,5] but instead get:
Error using strlength First argument must be text.
builtin('strlength', "hi")
expect value 2, but instead get
Error using strlength First argument must be text.