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

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!

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

10 Comments

This structure array does not work for vectors?
How can I create the array from a vector?
I have the vector:
x=[1 2 3 0]
I want to put it like this, but it doesn't work:
w=struct('name',{'apples' 'pears' 'melons' 'oranges'},'num',{x(1) x(2) x(3) x(4)})
fruit_names={w.name}
fruit_numbers=[w.num]
idx=max(fruit_numbers)
maximum=fruit_names{idx}
No it works
x=[1 2 3 0];
w=struct('name',{'apples' 'pears' 'melons' 'oranges'},'num',num2cell(x))
fruit_names={w.name}
fruit_numbers=[w.num]
idx=max(fruit_numbers)
maximum=fruit_names{idx}
It still doesn't run correctly. This is what I have:
for k=1:8
for j=1:4
for i=1:3
m1(i,j,k)=input('Goles equipo: ');
m2(i,j,k)=input('Goles otro: ');
if m1(i,j,k)>m2(i,j,k)
x(i,j,k)=3;
elseif m1(i,j,k)==m2(i,j,k)
x(i,j,k)=1;
elseif m1(i,j,k)<m2(i,j,k)
x(i,j,k)=0;
end
end
s(j,k)=x(1,j,k)+x(2,j,k)+x(3,j,k);
end
end
x=[s(1,1) s(2,1) s(3,1) s(4,1)];
w=struct('name',{'apples' 'pears' 'melons' 'oranges'},'num',num2cell(x))
fruit_names={w.name}
fruit_numbers=[w.num]
idx=max(fruit_numbers)
maximum=fruit_names{idx}
Index exceeds matrix dimensions. Error in marcadores (line 117) maximum=fruit_names{idx}
Change this line
idx=max(fruit_numbers)
to
[idx,idx]=max(fruit_numbers)
It works now! Thank you very very much!!

Sign in to comment.

More Answers (1)

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.

Tags

Community Treasure Hunt

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

Start Hunting!