How can I extract a word from a vector, instead of a number?

1 visualización (últimos 30 días)
apples=1;
pears=2;
melons=3;
oranges=0;
w=[apples pears melons oranges];
maximum=max(w)
Instead of getting a number, I want to get a word. That is, instead of getting "maximum=3", I want to get "maximum=melons"
Thanks!

Respuesta aceptada

Azzi Abdelmalek
Azzi Abdelmalek el 3 de Nov. de 2013
Editada: Azzi Abdelmalek el 3 de Nov. de 2013
Create a structure array with name and num fields.
w=struct('name',{'apples' 'pears' 'melons' 'oranges'},'num',{1 2 3 0})
fruit_names={w.name}
fruit_numbers=[w.num]
idx=max(fruit_numbers)
maximum=fruit_names{idx}
  10 comentarios
Azzi Abdelmalek
Azzi Abdelmalek el 4 de Nov. de 2013
Change this line
idx=max(fruit_numbers)
to
[idx,idx]=max(fruit_numbers)
Marcela Ruiz de Chávez
Marcela Ruiz de Chávez el 4 de Nov. de 2013
Editada: Marcela Ruiz de Chávez el 4 de Nov. de 2013
It works now! Thank you very very much!!

Iniciar sesión para comentar.

Más respuestas (1)

Walter Roberson
Walter Roberson el 3 de Nov. de 2013
You cannot do that with your setup. The "w" you construct only contains values and does not track any history of what variable names were used to construct the numeric vector.
You should have a look at containers.map -- though at the moment I do not know if it can handle 0 as the index.
What I would do would be:
fruitnames = {'oranges', 'apples', 'pears', 'melons'};
w = 0 : (length(fruitnames) - 1);
maximum = fruitnames{ 1 + max(w) };
or
maximum = fruitnames{end};
Note that maximum will end up as a string for this code.

Categorías

Más información sobre Numeric Types en Help Center y File Exchange.

Etiquetas

Community Treasure Hunt

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

Start Hunting!

Translated by