Oldest person in the room code not working

조회 수: 3 (최근 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
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 =
'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'}

카테고리

Help CenterFile Exchange에서 Cell Arrays에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by