MATLAB: How to extract a word from a vector, instead of a number

words

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!

Best Answer

  • 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}