findgroups

Assigns a group number to each element according to its unique value.

Category: Language Fundamentals > Data Types

Syntax

G = findgroups(A)

Returns the group index of each element of A.

[G, ID] = findgroups(A)

Also returns the unique values that identify the groups.

G = findgroups(A1, ..., AN)

Groups by the combination of several variables.

Description

findgroups is the first half of a split-apply-combine step. Pass G to splitapply or accumarray to compute a statistic per group, for instance the sum of values that share a label. Missing values (NaN) get a NaN group number.

Input arguments

A
Grouping variable: numeric, logical, string, categorical or cell array of character vectors. Must be a vector.

Output arguments

G
Column of positive integers, one per element of A; equal values share a number. Numbering follows the sorted order of the unique values.
ID
The unique values, sorted; ID(k) is the value of group k.

Example

Group and sum

[g, id] = findgroups(["b"; "a"; "b"; "c"])
accumarray(g, [1; 2; 3; 4])
Output
g = 4×1

     2
     1
     2
     3
id = 3×1 string array

    "a"
    "b"
    "c"
ans = 3×1

     2
     4
     4

See also

splitapply accumarray unique groupsummary groupcounts