MATLAB Examples

Common Indexing and Searching Methods

This example shows several common indexing and searching methods.

Load the sample data.

load carsmall;

Convert the char array, Origin, to a nominal array. This variable contains the country of origin, or manufacture, for each sample car.

Origin = nominal(Origin);

Search for observations in a category. Determine if there are any cars in the sample that were manufactured in Canada.

any(Origin=='Canada')
ans =

  logical

   0

There are no sample cars manufactured in Canada.

List the countries that are levels of Origin.

getlevels(Origin)
ans = 

  1x6 nominal array

     France      Germany      Italy      Japan      Sweden      USA 

Index elements that are in a particular category. Plot a histogram of the acceleration measurements for cars made in the U.S.

figure();
histogram(Acceleration(Origin=='USA'))
title('Acceleration of Cars Made in the USA')

Delete observations that are in a particular category. Delete all cars made in Sweden from Origin.

Origin = Origin(Origin~='Sweden');
any(ismember(Origin,'Sweden'))
ans =

  logical

   0

The cars made in Sweden are deleted from Origin, but Sweden is still a level of Origin.

getlevels(Origin)
ans = 

  1x6 nominal array

     France      Germany      Italy      Japan      Sweden      USA 

Remove Sweden from the levels of Origin.

Origin = droplevels(Origin,'Sweden');
getlevels(Origin)
ans = 

  1x5 nominal array

     France      Germany      Italy      Japan      USA 

Check for observations not in a defined category. Get the indices for the cars made in France.

ix = find(Origin=='France')
ix =

    11
    27
    39
    61

There are four cars from France. Remove France from the levels of Origin.

Origin = droplevels(Origin,'France');

This returns a warning indicating that you are dropping a category level that has elements in it. These observations are no longer in a defined category, indicated by undefined.

Origin(ix)
ans = 

  4x1 nominal array

     <undefined> 
     <undefined> 
     <undefined> 
     <undefined> 

You can use isundefined to search for observations with an undefined category.

find(isundefined(Origin))
ans =

    11
    27
    39
    61

These indices correspond to the observations that were in category France, before that category was dropped from Origin.