Effacer les filtres
Effacer les filtres

Assigne Values/Attribute to elements of an array

1 vue (au cours des 30 derniers jours)
luca
luca le 24 Juil 2019
Commenté : luca le 24 Juil 2019
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

Réponse acceptée

dpb
dpb le 24 Juil 2019
Modifié(e) : dpb le 24 Juil 2019
>> 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 commentaires
luca
luca le 24 Juil 2019
Modifié(e) : luca le 24 Juil 2019
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 le 24 Juil 2019
THANKS A LOT

Connectez-vous pour commenter.

Plus de réponses (0)

Catégories

En savoir plus sur Matrices and Arrays dans Help Center et File Exchange

Produits


Version

R2019a

Community Treasure Hunt

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

Start Hunting!

Translated by