MATLAB: Does converting a string array to a char array add a third dimension

MATLAB

Why does converting a string array to a char array add a third dimension?
e.g.
>> char(["0" "0" "0"])
1×1×3 char array
ans(:,:,1) =
'0'
ans(:,:,2) =
'0'
ans(:,:,3) =
'0'
I expect something more like
ans =
'000'

Best Answer

  • This is expected behavior for converting a horizontal string array to a char array. You can see this more clearly with an example where the input strings are of non-uniform length. The strings need to be converted to character arrays, but are in a single row vector (i.e. they are horizontally adjacent), so the resultant char arrays are concatenated in the 3rd dimension. If we tried to concatenate them in the second dimension (i.e. as columns), then we would lose the notion of distinct strings and would end up with something like 'abcdef' in the example below. Note also that string lengths are implicitly padded with spaces to make the matrix dimensions consistent.
    >> char(["abc","d","ef"])
    1×3×3 char array
    ans(:,:,1) =
    'abc'
    ans(:,:,2) =
    'd '
    ans(:,:,3) =
    'ef '
    Vertical string arrays are concatenated in the 1st dimension (i.e. as rows) since, in doing so, we still end up with distinct strings for each row.
    >> char(["abc";"d";"ef"])
    ans =
    3×3 char array
    'abc'
    'd '
    'ef '
    Note also that a i x j string matrix, whose longest element is length k will be converted to a i x k x j char matrix for the same reasons as above (i.e. we concatenate horizontally adjacent strings in the 3rd dimension, vertically adjacent strings in the 1st dimension, and we pad strings with spaces to make them a uniform length).
    I have linked the relevant documentation page below.