Oldest person in the room code not working

4 ビュー (過去 30 日間)
Takura Nyatsuro
Takura Nyatsuro 2022 年 6 月 28 日
回答済み: Geoff Hayes 2022 年 6 月 28 日
Hi there, I'm trying to find a solution I understand to a problem that asks me to find the oldest person in the room using 2 vectors , one to store the ages and one to store the names. The way i've gone about this is to find the position of the largest number in the age vector , then to take that position and translate it directly to the name vector to be able to loctae the oldest perosn. However, when i try to output the name i only get an output of single characters as matlab treats my name vector as a string of single characters , not 4 seperate names. Any help on how to fix the code would be appreciated thank you.
age = [23 56 24 55];
name = ['bob' 'bill' 'janice' 'kyle'];
position = find(age==max(age));
oldest = name(position)
oldest = 'o'

回答 (2 件)

Karim 2022 年 6 月 28 日
Hello, the issue is that the variable "name" is a char array in your case, hence it returns a char.
It will be easier to store the names as strings. By doing so you can use the same indexing to retrieve the full name. See below for the modified example
age = [23 56 24 55];
name = ["bob" "bill" "janice" "kyle"]; % <-- use " to create a string array
position = find(age==max(age));
oldest = name(position)
oldest = "bill"

Geoff Hayes
Geoff Hayes 2022 年 6 月 28 日
@Takura Nyatsuro - look closely at name
>> name = ['bob' 'bill' 'janice' 'kyle'];
>> name
name =
All the names have been concatenated together. I suggest that you change this from an array of characters to a cell array of names like
>> name = {'bob' 'bill' 'janice' 'kyle'}
name =
1×4 cell array
{'bob'} {'bill'} {'janice'} {'kyle'}


Find more on Cell Arrays in Help Center and File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by