splitapply

Applies a function to each group of data and collects the results.

Category: Language Fundamentals > Data Types

Syntax

Y = splitapply(func, X, G)

Splits X by the group numbers in G, calls func on each group and stacks the results.

[Y1, Y2, ...] = splitapply(func, X, G)

For a function that returns several outputs.

Description

splitapply is the second half of a split-apply-combine step: findgroups assigns an integer to each distinct key, and splitapply runs the function on the data of each group. The function is expected to return the same size for every group, typically a scalar such as sum, mean or numel.

Input arguments

func
Function handle applied to each group.
X
Data array, or several arrays X1, X2, ... if func takes several inputs. Groups are taken along the rows.
G
Positive integers giving the group of each row, usually from findgroups.

Output arguments

Y
One row per group, in group order.

Example

[g, id] = findgroups(["b";"a";"b"]);
id
splitapply(@sum, [10;20;30], g)
[m, i] = splitapply(@max, [3;9;4;1], [1;1;2;2])
Output
id = 2×1 string array

    "a"
    "b"
ans = 2×1

    20
    40
m = 2×1

     9
     4
i = 2×1

     2
     1

See also

findgroups groupsummary rowfun varfun accumarray unique