Main Content

Select Subsets of Observations

This example shows how to select an observation or subset of observations from a dataset array.

Load sample data.

Load the sample dataset array, hospital. Dataset arrays can have observation (row) names. This array has observation names corresponding to unique patient identifiers.

load hospital
ans = 10x1 cell

These are the first 10 observation names.

Index an observation by name.

You can use the observation names to index into the dataset array. For example, extract the last name, sex, and age for the patient with identifier XLK-030.

ans = 
               LastName         Sex       Age
    XLK-030    {'BROWN'}        Female    49 

Index a subset of observations by number.

Create a new dataset array containing the first 50 patients.

ds50 = hospital(1:50,:);
ans = 1×2

    50     7

Search observations using a logical condition.

Create a new dataset array containing only male patients. To find the male patients, use a logical condition to search the variable containing gender information.

dsMale = hospital(hospital.Sex=='Male',:);
ans = 
               LastName            Sex 
    YPL-320    {'SMITH'   }        Male
    GLI-532    {'JOHNSON' }        Male
    ATA-945    {'WILSON'  }        Male
    VNL-702    {'MOORE'   }        Male
    XUE-826    {'JACKSON' }        Male
    TRW-072    {'WHITE'   }        Male
    KOQ-996    {'MARTIN'  }        Male
    YUZ-646    {'THOMPSON'}        Male
    KPW-846    {'MARTINEZ'}        Male
    XBA-581    {'ROBINSON'}        Male

Search observations using multiple conditions.

You can use multiple conditions to search the dataset array. For example, create a new dataset array containing only female patients older than 40.

dsFemale = hospital(hospital.Sex=='Female' & hospital.Age > 40,:);
ans = 
               LastName            Sex       Age
    XLK-030    {'BROWN'   }        Female    49 
    TFP-518    {'DAVIS'   }        Female    46 
    QFY-472    {'ANDERSON'}        Female    45 
    UJG-627    {'THOMAS'  }        Female    42 
    BKD-785    {'CLARK'   }        Female    48 
    VWL-936    {'LEWIS'   }        Female    41 
    AAX-056    {'LEE'     }        Female    44 
    AFK-336    {'WRIGHT'  }        Female    45 
    KKL-155    {'ADAMS'   }        Female    48 
    RBA-579    {'SANCHEZ' }        Female    44 

Select a random subset of observations.

Create a new dataset array containing a random subset of 20 patients from the dataset array hospital.

rng('default') % For reproducibility
dsRandom = hospital(randsample(length(hospital),20),:);
ans = 20x1 cell

Delete observations by name.

Delete the data for the patient with observation name HVR-372.

hospital('HVR-372',:) = [];
ans = 1×2

    99     7

The dataset array has one less observation.

See Also

Related Examples

More About