%% Variance by Group
% Calculate group variances rather than sums.
% Create a vector of data and a matrix ind that defines groups of the data.

data = [100.1 101.2 103.4 102.8 100.9 101.5]'
ind = [1 1; 1 1; 2 2; 3 2; 2 2; 3 2]

% Compute the variance of each group by specifying the function handle @var as the method input. This syntax applies the var function to the groups instead of sum.

B1 = accumarray(ind,data,[],@var)

% You can specify the group computation as an anonymous function that accepts vector inputs and returns a scalar. This is useful when you want to pass additional arguments to a function. For example, use the var function with the normalization argument value 1.

A2 = accumarray(ind,data,[],@(x) var(x,1))

% Copyright 2020 The MathWorks, Inc.