Oldest person in the room code not working
3 visualizaciones (últimos 30 días)
Mostrar comentarios más antiguos
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)
0 comentarios
Respuestas (2)
Karim
el 28 de Jun. de 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)
0 comentarios
Geoff Hayes
el 28 de Jun. de 2022
>> name = ['bob' 'bill' 'janice' 'kyle'];
>> name
name =
'bobbilljanicekyle'
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'}
0 comentarios
Ver también
Categorías
Más información sobre Cell Arrays en Help Center y File Exchange.
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!