2

I have a 3 x n array in matlab. I want to create a new 4 x n array that contains all the unique combinations of rows 1 and 2, the sum of the third column for each combination and how many times these unique combinations exist (to get the mean value later).

Is there an efficient way to do this, without using two nested for loops?

Edit: All three rows are numerical values (integers). I used a,b,c,d just for demonstration purposes.

For example:

Unprocessed matrix:  
a b b d a a d d    
a c d d d a d d    
5 5 5 5 5 5 5 5

New matrix:
a  b  b  d  a   
a  c  d  d  d    
10 5  5  15 5    
2  1  1  3  1
Robert Seifert
  • 25,078
  • 11
  • 68
  • 113

1 Answers1

2

Classic accumarray job:

A =  [1 2 2 4 1 1 4 4    
      1 3 4 4 4 1 4 4    
      5 5 5 5 5 5 5 5]

A = A.' %'
[u,~,subs] = unique(A(:,[1,2]),'rows')
sums = accumarray(subs(:),A(:,3))
occs = accumarray(subs(:),A(:,3),[],@numel)

out = [u, (sums./occs), occs].'

out =

     1     1     2     2     4
     1     4     3     4     4
     5     5     5     5     5
     2     1     1     1     3

If you insist on the order in your example, then you need the 'stable' propery of unique and a stable accumarray as well.

Community
  • 1
  • 1
Robert Seifert
  • 25,078
  • 11
  • 68
  • 113