Home > Net >  Since a string scalar is a sequence or array of characters, why do we still need character vector as
Since a string scalar is a sequence or array of characters, why do we still need character vector as

Time:12-01

For string scalar like "abc" which is an array of characters 'a', 'b', 'c', but for character vector like 'abc', is this also an array of characters? Why do we need two types of data to preserve the same message?

CodePudding user response:

The single quote version is the historical method, and is a rectangular array of characters. If all you want to store is a single string, this works fine. But if you want to store multiple strings in the same variable, the rectangular array becomes less useful because you have to pad blanks on the shorter strings to get everything to fit in the rectangular array. Also each individual string held as a row of the array is not contiguous in memory.

This led to using cell arrays for holding multiple strings of different lengths in the same variable. However, that also has drawbacks because each string is required to have it's own variable header (> 100 bytes), so there are performance impacts.

The double quote string is a relatively recent class introduced by MATLAB for holding multiple strings in a single variable. The individual strings are held in memory in contiguous chunks without the need for individual variable headers, and the operations on them are more optimized as a result.

MATLAB will no doubt continue to support all three methods in the future for backward compatability.

  • Related