Convert string arrays to character arrays, leaving other arrays unaltered
When working with your own code, you can use
convertStringsToChars
to make your code accept string inputs.
Then you do not have to make any other changes to code that you had written to work with
character arrays.
[B1,...,Bn] = convertStringsToChars(A1,...,An)
converts any
string arrays in A1,...,An
to character vectors or cell arrays of
character vectors, and then returns them as the corresponding output arguments in
B1,...,Bn
. If any of the arguments
A1,...,An
has any other data type, then
convertStringsToChars
returns it unaltered.
To enable your existing code to accept string arrays as input, add a call to
convertStringsToChars
at the beginning of your
code.
For example, if you have defined a function myFunc
that
accepts three input arguments, process all three inputs using
convertStringsToChars
. Leave the rest of your code
unchanged.
function y = myFunc(a,b,c) [a,b,c] = convertStringsToChars(a,b,c); <line 1 of original code> <line 2 of original code> ...
In this example, the output arguments [a,b,c]
overwrite the
input arguments in place. If any input argument is not a string array, then it
is unaltered.
If myFunc
accepts a variable number of input arguments,
then process all the arguments specified by
varargin
.
function y = myFunc(varargin) [varargin{:}] = convertStringsToChars(varargin{:}); ...
The convertStringsToChars
function is more efficient when
converting one input argument. If performance is a concern, then call
convertStringsToChars
on one input argument at a time,
rather than calling it once on multiple inputs.
convertCharsToStrings
| convertContainedStringsToChars
| isStringScalar
| iscellstr
| ischar
| ismissing
| isstring
| string
| varargin