Effacer les filtres
Effacer les filtres

Oldest person in the room code not working

2 vues (au cours des 30 derniers jours)
Takura Nyatsuro
Takura Nyatsuro le 28 Juin 2022
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'

Réponses (2)

Karim le 28 Juin 2022
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 le 28 Juin 2022
@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'}

Community Treasure Hunt

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

Start Hunting!

Translated by