0

Looking at following code:

x=[2,3;1,4;1,5;2,4;3,1;3,4];
u=unique(x(:,1));
for i=1:length(u)
    n(i,:)=mean(x(x(:,1)==u(i),:))
end

Is there anyway to avoid the for loop, and make the code simpler? Basically, what I want to do is to group the rows based on a the value of a column and apply an operation on the other values for a given "group".

Adriaan
  • 17,741
  • 7
  • 42
  • 75
Amir
  • 5,996
  • 13
  • 48
  • 61
  • 3
    Possible duplicate of [MATLAB find and apply function to values of repeated indices](http://stackoverflow.com/questions/16086874/matlab-find-and-apply-function-to-values-of-repeated-indices) – marsei Dec 22 '15 at 22:14
  • the answer: http://stackoverflow.com/a/16087141/1904719 – marsei Dec 22 '15 at 22:20

1 Answers1

2

That's a job for the powerful accumarray with the mean function. Basically use values in the 1st column of x as subscripts and the values from the 2nd column as actual values on which you perform the desired calculation:

n2 = accumarray((x(:,1)),x(:,2),[],@mean)

out = [unique(x(:,1)) n2]

out =

    1.0000    4.5000
    2.0000    3.5000
    3.0000    2.5000

yay!

Benoit_11
  • 13,905
  • 2
  • 24
  • 35