Assigne Values/Attribute to elements of an array

2 次查看(过去 30 天)
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

请先登录,再进行评论。

更多回答(0 个)

类别

Help CenterFile Exchange 中查找有关 Categorical Arrays 的更多信息

产品


版本

R2019a

Community Treasure Hunt

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

Start Hunting!

Translated by