Conversion of Categorical to char while maintaining same dimension

37 ビュー (過去 30 日間)
NAVNEET NAYAN
NAVNEET NAYAN 2024 年 3 月 9 日
コメント済み: Voss 2024 年 3 月 10 日
I have a variable having dimension m-by-3. It's datatype is categorical. I am trying to convert it to char datatype while maintaining the same dimension of m-by-3.
Can someone tell me how to convert a variable of categorical datatype of dimension m-by-3 to the char datatype of dimension m-by-3?

採用された回答

Voss
Voss 2024 年 3 月 9 日
You cannot do that in general.
In the special case that all the categories are a single character long, then you can do it:
m = 4;
% creating a random m-by-3 categorical array
C = categorical(num2cell(char(64+randi(26,[m 3]))))
C = 4×3 categorical array
T Z H G X W P N R X Y Y
% converting C to an m-by-3 char
reshape(char(C),m,[])
ans = 4×3 char array
'TZH' 'GXW' 'PNR' 'XYY'
But if any of the categories is more than one character, that's not going to work because you have more than 3*m characters in total.
Instead, convert to a string array:
string(C) % m-by-3 string array
ans = 4×3 string array
"T" "Z" "H" "G" "X" "W" "P" "N" "R" "X" "Y" "Y"
Or a cell array of character vectors:
cellstr(C) % m-by-3 cell array
ans = 4×3 cell array
{'T'} {'Z'} {'H'} {'G'} {'X'} {'W'} {'P'} {'N'} {'R'} {'X'} {'Y'} {'Y'}
  2 件のコメント
NAVNEET NAYAN
NAVNEET NAYAN 2024 年 3 月 10 日
Very well explained. Thank You So Much.
Voss
Voss 2024 年 3 月 10 日
You're welcome!

サインインしてコメントする。

その他の回答 (0 件)

カテゴリ

Help Center および File ExchangeCategorical Arrays についてさらに検索

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by