Borrar filtros
Borrar filtros

Assigne Values/Attribute to elements of an array

1 visualización (últimos 30 días)
luca
luca el 24 de Jul. de 2019
Comentada: luca el 24 de Jul. de 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

Respuesta aceptada

dpb
dpb el 24 de Jul. de 2019
Editada: dpb el 24 de Jul. de 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 comentarios
luca
luca el 24 de Jul. de 2019
Editada: luca el 24 de Jul. de 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 el 24 de Jul. de 2019
THANKS A LOT

Iniciar sesión para comentar.

Más respuestas (0)

Categorías

Más información sobre Matrices and Arrays en Help Center y File Exchange.

Productos


Versión

R2019a

Community Treasure Hunt

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

Start Hunting!

Translated by