MATLAB Examples

Common Indexing and Searching Methods

This example shows several indexing and searching methods for categorical arrays.

Load the sample data.

load hospital;
ans =

   100     7

The dataset array has 100 observations and 7 variables.

Index a variable by name. Return the minimum age in the dataset array.

ans =


Delete the variable Trials.

hospital.Trials = [];
ans =

   100     6

Index an observation by name. Display measurements on the first five variables for the observation named PUE-347.

ans = 

               LastName       Sex       Age    Weight    Smoker
    PUE-347    'YOUNG'        Female    25     114       false 

Index variables by number. Create a new dataset array containing the first four variables of hospital.

dsNew = hospital(:,1:4);
ans =

  4x1 cell array

    {'Sex'     }
    {'Age'     }
    {'Weight'  }

Index observations by number. Delete the last 10 observations.

hospital(end-9:end,:) = [];
ans =

    90     6

Search for observations by logical condition. Create a new dataset array containing only females who smoke.

dsFS = hospital(hospital.Sex=='Female' & hospital.Smoker==true,:);
ans = 

               LastName           Sex       Smoker
    LPD-746    'MILLER'           Female    true  
    XBR-291    'GARCIA'           Female    true  
    AAX-056    'LEE'              Female    true  
    DTT-578    'WALKER'           Female    true  
    AFK-336    'WRIGHT'           Female    true  
    RBA-579    'SANCHEZ'          Female    true  
    HAK-381    'MORRIS'           Female    true  
    NSK-403    'RAMIREZ'          Female    true  
    ILS-109    'WATSON'           Female    true  
    JDR-456    'SANDERS'          Female    true  
    HWZ-321    'PATTERSON'        Female    true  
    GGU-691    'HUGHES'           Female    true  
    WUS-105    'FLORES'           Female    true