Char function for a cell array
5 views (last 30 days)
Show older comments
Hello! I have a problem with converting an cell array to a char array and then from vertical to horizontal.
%So the results look like:
MGFS
AEIL
TAVO
EREW
%instead : MATE GEAR FIVE SLOW
Can not find out where is my mistake. For example:
Name = [ MATE %this is my array of cell type. It is vertically
GEAR
FIVE
SLOW
]
Name_new = (Name).' %trying to transpose from vertical into a horizontal array, the type of the data is still cell
Names = char(Name_new)
% and the results are :
MGFS
AEIL
TAVO
EREW
%instead : MATE GEAR FIVE SLOW
I have tryied to transpose Name array without coma after it, I mean :
Name_new = (Name)'
but the results are the same ....
Answers (2)
dpb
on 11 Dec 2018
The cell array would be
>> Name = {'MATE'; 'GEAR'; 'FIVE'; 'SLOW'} % define column cellstr array
Name =
4×1 cell array
{'MATE'}
{'GEAR'}
{'FIVE'}
{'SLOW'}
>> Name=Name.' % transpose to row
Name =
1×4 cell array
{'MATE'} {'GEAR'} {'FIVE'} {'SLOW'}
>> Name=string(Name) % use the new strings class instead...
Name =
1×4 string array
"MATE" "GEAR" "FIVE" "SLOW"
>> Name=Name.' % it also transposes as wish
Name =
4×1 string array
"MATE"
"GEAR"
"FIVE"
"SLOW"
>> cName=char(Name) % convert to a char() array
cName =
4×4 char array
'MATE'
'GEAR'
'FIVE'
'SLOW'
>> cName.' % char() arrays are just a 2D array of bytes...
ans =
4×4 char array
'MGFS'
'AEIL'
'TAVO'
'EREW'
>>
In general, you don't want to even try to handle character data as char() arrays any more--they're a remnant of the earliest releases of Matlab before there were cellstr() and the later string(). As the above shows, they are simply a 2D array of bytes displayed as the character representation instead of numeric but array operations on them are as for any other array; storage is in column-major order so the transpose above turns the strings from rows to columns containing the characters.
To reference any given string out of a char() array requires 2D array syntax:
>> cName(3,:)
ans =
'FIVE'
>>
NB: the colon to get all the elements of all the columns for the third row...
0 Comments
Star Strider
on 11 Dec 2018
Try this:
Name = {'MATE' 'GEAR' 'FIVE' 'SLOW'};
Name = reshape(Name, [], 1);
NameC = cell2mat(Name)
producing:
NameC =
4×4 char array
'MATE'
'GEAR'
'FIVE'
'SLOW'
0 Comments
See Also
Categories
Find more on Data Type Conversion in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!