Section 3.2 Arrays of Strings
Arrays of strings (when using character arrays to store each string) are relatively tricky in MATLAB.
You can make an array of strings from individual strings but you must be sure to pad strings with spaces to make sure they are all the same size.
If all your strings are of the same size there is no problem:
>> var_name = ['string1'; 'string2'; 'string3']
var_name =
3×7 char array
'string1'
'string2'
'string3'
If the individual strings are not of the same length then you get into trouble:
>> badarray = ['a'; 'ab'; 'abc']
One way to deal with this issue is to pad the shorter strings with spaces:
>> goodarray = ['a '; 'ab '; 'abc']
goodarray =
3×3 char array
'a '
'ab '
'abc'
Since this is not great, MATLAB provides a function to help, the
char()
function which does the padding for you:>> alternative = char('a', 'ab', 'abc')
alternative =
3×3 char array
'a '
'ab '
'abc'
>> info = char('Taylor', 'Petra', 'C+')
info =
3×6 char array
'Taylor'
'Petra '
'C+ '