MATLAB Programming Fundamentals - MathWorks

(やまだぃちぅ) #1
character vector (using single quotes). Best practice is to update the function so
that the argument can be specified as either a character vector or a string scalar
(using double quotes).


  • Accept strings as both names and values in name-value pair arguments.

    • In name-value pair arguments, allow names to be specified as either character
      vectors or strings—that is, with either single or double quotes around the name. If
      a value can be a character vector or cell array of character vectors, then update
      your code so that it also can be a string array.



  • Do not accept cell arrays of string arrays for text input arguments.

    • A cell array of string arrays has a string array in each cell. For example,
      {"hello","world"} is a cell array of string arrays. While you can create such a
      cell array, it is not recommended for storing text. The elements of a string array
      have the same data type and are stored efficiently. If you store strings in a cell
      array, then you lose the advantages of using a string array.




However, if your code accepts heterogeneous cell arrays as inputs, then consider
accepting cell arrays that contain strings. You can convert any strings in such a cell
array to character vectors.


  • In general, do not change the output type.

    • If your function returns a character vector or cell array of character vectors, then
      do not change the output type, even if the function accepts string arrays as inputs.
      For example, the fileread function accepts an input file name specified as either
      a character vector or a string, but the function returns the file contents as a
      character vector. By keeping the output type the same, you can maintain backward
      compatibility.



  • Return the same data type when the function modifies input text.

    • If your function modifies input text and returns the modified text as the output
      argument, then the input and output arguments should have the same data type.
      For example, the lower function accepts text as the input argument, converts it to
      all lowercase letters, and returns it. If the input argument is a character vector,
      then lower returns a character vector. If the input is a string array, then lower
      returns a string array.



  • Consider adding a 'TextType' argument to import functions.

    • If your function imports data from files, and at least some of that data can be text,
      then consider adding an input argument that specifies whether to return text as a




Update Your Code to Accept Strings
Free download pdf