What is the difference between strings and characters in Matlab?

前端 未结 4 1230
北荒
北荒 2020-12-14 04:46

What is the difference between string and character class in MATLAB?

a = \'AX\'; % This is a character.
b = string(a) % This is a string.
4条回答
  •  情话喂你
    2020-12-14 05:08

    The best place to start for understanding the difference is the documentation. The key difference, as stated there:

    • A character array is a sequence of characters, just as a numeric array is a sequence of numbers. A typical use is to store short pieces of text as character vectors, such as c = 'Hello World';.
    • A string array is a container for pieces of text. String arrays provide a set of functions for working with text as data. To convert text to string arrays, use the string function.

    Here are a few more key points about their differences:

    • They are different classes (i.e. types): char versus string. As such they will have different sets of methods defined for each. Think about what sort of operations you want to do on your text, then choose the one that best supports those.
    • Since a string is a container class, be mindful of how its size differs from an equivalent character array representation. Using your example:

      >> a = 'AX'; % This is a character.
      >> b = string(a) % This is a string.
      >> whos
        Name      Size            Bytes  Class     Attributes
      
        a         1x2                 4  char                
        b         1x1               134  string
      

      Notice that the string container lists its size as 1x1 (and takes up more bytes in memory) while the character array is, as its name implies, a 1x2 array of characters.

    • They can't always be used interchangeably, and you may need to convert between the two for certain operations. For example, string objects can't be used as dynamic field names for structure indexing:

      >> s = struct('a', 1);
      >> name = string('a');
      >> s.(name)
      Argument to dynamic structure reference must evaluate to a valid field name.
      
      >> s.(char(name))
      
      ans =
      
           1
      

提交回复
热议问题