MATLAB: Can this silly accumarray for-loop be removed by a vectorization

accumarrayfor loopMATLABoptimizationvectorization

I have a matrix A where some of the values in column 1 are duplicates. Where a duplicate exists in column 1 (representing a timestamp) I want to replace the corresponding values in the other columns by a mean value of the duplicates.
Right now Im doing it by identifying the unique values and then loop through the columns one by one via a temporary variable since accumarray only accepts one column at a time:
[UA,~,idx] = unique(A(:,1)); % Finds duplicates in the first column of matrix A
for i = 28:-1:2
Temp = [UA,accumarray(idx,A(:,i),[],@mean)]; % Replaces duplicates with the mean of the duplicate values in column i
B(:,i) = Temp(:,2); % Transfers the results and builds the final matrix B containing the same as A but with no duplicates
end
It is doing what I want but it is really slow, is there any simple way of rewriting it so I don’t have to deal with the for-loop?

Best Answer

A = randi(32280,28);
[UA,~,idx] = unique(A(:,1));
[X,Y] = ndgrid(idx, 2:size(A,2));
newcolumns = accumarray([X(:), Y(:)], reshape(A(:,2:end),[],1), [], @mean);
The ndgrid needs to start in the second column and only extract the 2nd through end columns of A for vals.