Filter löschen
Filter löschen

Assigne Values/Attribute to elements of an array

1 Ansicht (letzte 30 Tage)
luca
luca am 24 Jul. 2019
Kommentiert: luca am 24 Jul. 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

Akzeptierte Antwort

dpb
dpb am 24 Jul. 2019
Bearbeitet: dpb am 24 Jul. 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 Kommentare
luca
luca am 24 Jul. 2019
Bearbeitet: luca am 24 Jul. 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 am 24 Jul. 2019
THANKS A LOT

Melden Sie sich an, um zu kommentieren.

Weitere Antworten (0)

Kategorien

Mehr zu Matrices and Arrays finden Sie in Help Center und File Exchange

Produkte


Version

R2019a

Community Treasure Hunt

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

Start Hunting!

Translated by