필터 지우기
필터 지우기

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

조회 수: 1 (최근 30일)
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!

채택된 답변

Azzi Abdelmalek
Azzi Abdelmalek 2013년 11월 3일
편집: Azzi Abdelmalek 2013년 11월 3일
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
Azzi Abdelmalek
Azzi Abdelmalek 2013년 11월 4일
Change this line
idx=max(fruit_numbers)
to
[idx,idx]=max(fruit_numbers)
Marcela Ruiz de Chávez
Marcela Ruiz de Chávez 2013년 11월 4일
편집: Marcela Ruiz de Chávez 2013년 11월 4일
It works now! Thank you very very much!!

댓글을 달려면 로그인하십시오.

추가 답변 (1개)

Walter Roberson
Walter Roberson 2013년 11월 3일
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.

카테고리

Help CenterFile Exchange에서 Characters and Strings에 대해 자세히 알아보기

태그

Community Treasure Hunt

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

Start Hunting!

Translated by