What is the difference between string and character class in MATLAB?
a = 'AX'; % This is a character.
b = string(a) % This is a string.
What is the difference between string and character class in MATLAB?
a = 'AX'; % This is a character.
b = string(a) % This is a string.
The documentation suggests:
This is how the two representations differ:
Element access. To represent
char
vectors of different length, one had to usecell
arrays, e.g.ch = {'a', 'ab', 'abc'}
. With strings, they can be created in actual arrays:str = [string('a'), string('ab'), string('abc')]
. However, to index characters in a string array directly, the curly bracket notation has to be used:Memory use. Chars use exactly as many bytes as there are characters.
string
s have overhead:returns
The best place to start for understanding the difference is the documentation. The key difference, as stated there:
Here are a few more key points about their differences:
char
versusstring
. 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:Notice that the
string
container lists its size as1x1
(and takes up more bytes in memory) while the character array is, as its name implies, a1x2
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:Strings do have a bit of overhead, but still increase by 2 bytes per character. After every 8 characters it increases the size of the variable. The red line is
y=2x+127
.figure is created using: