MATLAB Programming Fundamentals - MathWorks

(やまだぃちぅ) #1

accept string arrays as inputs, add a call to convertStringsToChars 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 convertStringsToChars. Leave the rest of your code
unaltered.


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 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{:});
...


Performance Considerations


The convertStringsToChars 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 = convertStringsToChars(a);
b = convertStringsToChars(b);
c = convertStringsToChars(c);
...


Recommended Approaches for String Adoption in New Code


When your code has few dependencies, or you are developing entirely new code, consider
using strings arrays as the primary text data type. String arrays provide good
performance and efficient memory usage when working with large amounts of text.
Unlike cell arrays of character vectors, string arrays have a homogenous data type. String
arrays make it easier to write maintainable code. To use string arrays while maintaining
backward compatibility to other text data types, follow these approaches.


Update Your Code to Accept Strings
Free download pdf