ag14
ag14

Reputation: 867

MATLAB table - Select first row that meets a condition

I want to select the first row that meets a certain condition. For instance lets consider the MATLAB patients sample data

load patients
patients = table(LastName,Age,Gender,Height,Weight,Smoker);

I want to select the first row that meets the condition of Gender being 'Male' and Age > 40. This would result in the patient named "Johnson" being selected.

subset_patients = patients(strcmp(patients.Gender, 'Male') & patients.Age>40,:)
first_Male_over40 = subset_patients(1,:);

Is there a way to do it in one line though, so I do not waste space creating a separate table for the subset? I tried the following but it did not work.

first_Male_over40 = patients(strcmp(patients.Gender, 'Male') & patients.Age>40,:)(1,:);

Upvotes: 1

Views: 222

Answers (1)

Muttley
Muttley

Reputation: 512

You can use find(logicalIndexes, k, 'first') as follows (k=1 in your case):

first_Male_over40 = patients(find(strcmp(patients.Gender, 'Male') & (patients.Age > 40), 1, 'first'), :)

Upvotes: 2

Related Questions