MATLAB Programming Fundamentals - MathWorks

(やまだぃちぅ) #1

How to Maintain Compatibility in New Code


When you write new code, or modify code to use string arrays as the primary text data
type, maintain backward compatibility with other text data types. You can accept
character vectors or cell arrays of character vectors as input arguments, and then
immediately convert them to string arrays. If you perform such a conversion at the start
of a function, then the rest of your code can use string arrays only.


The convertCharsToStrings function provides a way to process all input arguments,
converting only those arguments that are character vectors or cell arrays of character
vectors. To enable your new code to accept these text data types as inputs, add a call to
convertCharsToStrings at the beginnings of your functions and methods.


For example, if you have defined a function myFunc that accepts three input arguments,
process all three inputs using convertCharsToStrings.


function y = myFunc(a,b,c)
[a,b,c] = convertCharsToStrings(a,b,c);
<line 1 of original code>
<line 2 of original code>
...


In this example, the arguments [a,b,c] overwrite the input arguments in place. If any
input argument is not a character vector or cell array of character vectors, 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{:}] = convertCharsToStrings(varargin{:});
...


Performance Considerations


The convertCharsToStrings function is more efficient when converting one input
argument. If your function is performance sensitive, then you can convert input
arguments one at a time, while still leaving the rest of your code unaltered.


function y = myFunc(a,b,c)
a = convertCharsToStrings(a);
b = convertCharsToStrings(b);
c = convertCharsToStrings(c);
...


Update Your Code to Accept Strings
Free download pdf