Quantcast

Documentation Center

  • Trial Software
  • Product Updates

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, or logical vector; a cell vector of strings; or a character matrix 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 strings 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 string 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 or logical), empty strings (char or cell array of strings), or <undefined> values (categorical) 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

See Also

| | |

Was this topic helpful?