필터 지우기
필터 지우기

Assigne Values/Attribute to elements of an array

조회 수: 1 (최근 30일)
luca
luca 2019년 7월 24일
댓글: luca 2019년 7월 24일
Hi,
I have a vector v = [1 2 3 4 5] and I want to assign attributes to each of the value of the vector.
It means that every time I recall in a loop cycle one of the vector's element, I want also the possibility to recognize its attribute in the loop. The elements in the vector are numbers and not strings. 1 needs attribute A, 2 needs attribute B, 3 needs attribute C, 4 needs attribute D and 5 needs attribute E. So MATLAB should know that when I call 1, it brings with him the value A (its attribute).
Thanks

채택된 답변

dpb
dpb 2019년 7월 24일
편집: dpb 2019년 7월 24일
>> V = categorical(v,v,cellstr(['A':'E'].'))
V =
1×5 categorical array
A B C D E
>>
ADDENDUM:
To answer the follow-up--
Of course it does...with some slight modification to match the documentation of how categorical array generation works in general case... :)
v=[1:4 1]; % the initial numeric vector with duplicated entry
c=['A':'Z'].'; % the population of categorical labels
u=unique(v); % unique elements in initial vector
>> V = categorical(v,u,cellstr(c(u))) % create categorical vector V from v
V =
1×5 categorical array
A B C D A
>>
As the doc says, the second argument is unique() of the first by default and can be omitted if don't need the third to assign category names different from the values as do here. So, you have to do that yourself...and, of course, have a way to look up what the category name is supposed to be for each element in the original array.
  댓글 수: 2
luca
luca 2019년 7월 24일
편집: luca 2019년 7월 24일
I have one futher question. if the Vector v=[1 2 3 4 1], so it has duplicates, your method does not work. Do you have a solution?
If at the fifth position it found again 1, I need to display again A
luca
luca 2019년 7월 24일
THANKS A LOT

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

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Matrices and Arrays에 대해 자세히 알아보기

제품


릴리스

R2019a

Community Treasure Hunt

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

Start Hunting!

Translated by