fixed iteration through groups in average_matrix()