Casting a number into a categorical array

Hello,
I'm trying to swith my project to categorical arrays (from a cellstr plus a numeric index). There's one feature that should be insanely simple, but I can't find a simple way to do it. I'd like to be able to cast a number or char into an existing type of categorical array. In other words, given a categorical array x, I'd like to take a number vector or cellstr y, and produce a categorical array with the categories of x (in the same order), but the entries in y:
x = categorical({'one','two','three'})
y1 = [2,2,3]
y2 = {'two','two','three'}
categorical(y1, double(x), categories(x)) % works, but is super lengthy, data-type specific, and probably inefficient
categorical(y2, cellstr(char(x)), categories(x)) % doesn't even work (returns a categorical array valued [three,three,two])
The motivation is to acquire two arrays that index into the same list of categories. Any advice appreciated!

댓글 수: 1

E
E 2022년 6월 13일
(FYI I'd use an enum, but the list of categories is determined dynamically)

댓글을 달려면 로그인하십시오.

 채택된 답변

Stephen23
Stephen23 2022년 6월 13일
x = categorical({'one','two','three'})
x = 1×3 categorical array
one two three
c = categories(x)
c = 3×1 cell array
{'one' } {'three'} {'two' }
y = setcats(categorical({'two','two','three'}),c)
y = 1×3 categorical array
two two three
d = categories(y)
d = 3×1 cell array
{'one' } {'three'} {'two' }

추가 답변 (0개)

카테고리

도움말 센터File Exchange에서 Categorical Arrays에 대해 자세히 알아보기

제품

릴리스

R2021a

질문:

E
E
2022년 6월 13일

댓글:

E
E
2022년 6월 13일

Community Treasure Hunt

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

Start Hunting!

Translated by