Char function for a cell array
5 次查看(过去 30 天)
显示 更早的评论
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 ....
回答(2 个)
dpb
2018-12-11
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 个评论
Star Strider
2018-12-11
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 个评论
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Whos 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!