Documentation

This is machine translation

Translated by Microsoft
Mouse over text to see original. Click the button below to return to the English verison of the page.

grp2idx

Create index vector from grouping variable

Syntax

[G,GN]=grp2idx(S)
[G,GN,GL] = grp2idx(S)

Description

[G,GN]=grp2idx(S) creates an index vector G from the grouping variable S. S can be a categorical, numeric, logical, datetime, or duration vector; a cell array of character vectors; or a character array with each row representing a group label. The result G is a vector taking integer values from 1 up to the number K of distinct groups. GN is a cell array of character vectors representing group labels. GN(G) reproduces S (aside from any differences in type).

The order of GN depends on the grouping variable:

  • For numeric and logical grouping variables, the order is the sorted order of S.

  • For categorical grouping variables, the order is the order of getlabels(S).

  • For grouping variables, the order is the order of first appearance in S.

[G,GN,GL] = grp2idx(S) returns a column vector GL representing the group levels. The set of groups and their order in GL and GN are the same, except that GL has the same type as S. If S is a character matrix, GL(G,:) reproduces S, otherwise GL(G) reproduces S.

grp2idx treats NaNs (numeric, duration, or logical), ' ' (empty character arrays or cell arrays of character vectors), <undefined> values (categorical), and NaTs (datetime) in S as missing values and returns NaNs in the corresponding rows of G. GN and GL don't include entries for missing values.

Examples

Load the data in hospital.mat and create a categorical grouping variable:

load hospital
edges = 0:10:100;
labels = strcat(num2str((0:10:90)','%d'),{'s'});
AgeGroup = ordinal(hospital.Age,labels,[],edges);

ages = hospital.Age(1:5)
ages =
    38
    43
    38
    40
    49
group = AgeGroup(1:5)
group = 
     30s 
     40s 
     30s 
     40s 
     40s 
indices = grp2idx(group)
indices =
     4
     5
     4
     5
     5

Introduced before R2006a

Was this topic helpful?