Why does converting a string array to a char array add a third dimension?
9 vues (au cours des 30 derniers jours)
Afficher commentaires plus anciens
MathWorks Support Team
le 10 Juin 2019
Modifié(e) : MathWorks Support Team
le 29 Août 2024
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'
Réponse acceptée
MathWorks Support Team
le 29 Juil 2024
Modifié(e) : MathWorks Support Team
le 29 Août 2024
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).
To find the relevant documentation link, please run the below command in the command window of installed MATLAB R2019a version to get release specific documentation:
>> web(fullfile(docroot, 'matlab/ref/char.html'))
Please follow the below link to search for the required information regarding the current release:
0 commentaires
Plus de réponses (0)
Voir également
Catégories
En savoir plus sur Characters and Strings dans Help Center et File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!