accumarray
Groups values by index and sums each group.
Category: Data Import and Analysis > Preprocessing Data
Syntax
A = accumarray(subs, vals)
Adds up the elements of vals that share the same value in subs.
Description
accumarray is a compact way to compute group totals, a histogram with weights, or a count per category. Think of subs as group labels and vals as the data: the output at position k collects everything labeled k.
Using a scalar for vals counts how many times each index occurs (with vals = 1).
Input arguments
subs- Column vector of positive integer indices; each says which output element receives the matching value.
vals- Column vector of values, one per index, or a scalar that is added once per index.
Output arguments
A- Column vector whose length is
max(subs); elementkis the sum of the values whose index isk. Positions that never appear hold0.
Example
Totals per group
subs = [1; 2; 1; 3];
vals = [10; 20; 30; 40];
accumarray(subs, vals)
accumarray([2; 3; 3; 3], 1)
Output
ans = 3×1
40
20
40
ans = 3×1
0
1
3