MATLAB Answers


How to use accumarray?

Asked by Ede gerlderlands on 30 Jun 2013

I have a matrix of y=[9, 5346]

I want to find the the mean of every six values of each row. I tried this function but can't really figure out how to do it

 for ii=1:9

it's saying there is error in this code . I don't really know how this accumarray works.

Any help is appreciated



No products are associated with this question.

2 Answers

Answer by the cyclist
on 30 Jun 2013
Edited by the cyclist
on 30 Jun 2013
 Accepted answer

accumarray() can be a bit tricky to learn. I think this solves your problem. I commented it to help you see what is happening.

A = rand(9,5346); % Make up some fake data that is the same size as yours
At = A'; % Take the transpose, because accumarray works down columns.
numberPerGroup = 6;
numberGroups = 5346/6; % 931, but wanted you to see where this comes from
% The subs array indicates which rows (of the transposed array) are going to get grouped. You have 931 groups total, each gather 6 rows.
subs = repmat(1:numberGroups,[numberPerGroup,1]);
subs = subs(:);
% Preallocate the output array
output = zeros(numberGroups,9);
% Accumulate each column in turn
for nr = 1:9
    output(:,nr) = accumarray(subs,At(:,nr),[],@mean);
% Transpose the output back
output = output';

  1 Comment

Thank you ..

Answer by Matt J
on 30 Jun 2013

Although you can do this with accumarray, it will probably be faster to do


using the function below.

function M=downsampn(M,bindims)
%DOWNSAMPN - simple tool for downsampling n-dimensional nonsparse arrays
%  M=downsampn(M,bindims)
% M: an array
% bindims: a vector of integer binning dimensions
% M: the downsized array
[sz{1:nn}]=size(M); %M is the original array
for ii=1:nn

  1 Comment

Yes, thank you.

Join the 15-year community celebration.

Play games and win prizes!

Learn more
Discover MakerZone

MATLAB and Simulink resources for Arduino, LEGO, and Raspberry Pi

Learn more

Discover what MATLAB® can do for your career.

Opportunities for recent engineering grads.

Apply Today

MATLAB Academy

New to MATLAB?

Learn MATLAB today!