title: Grouping by nested unique values
body: <p>I have a matrix A in Matlab:</p>
  
  <pre><code>A = [176  5406  1  4  7903;
       155  5406  1  5  7903;
       122  5407  0  4  7903;
       140  5407  0  5  7904;
       130  5407  0  3  7904];
  </code></pre>
  
  <p>Just for information - the second column is a user ID, while the fourth column is a time. So <code>5406</code> is one user and <code>5407</code> is another user. Both of these users have some information stored in the first column and the 4th column which I am interested in accessing. </p>
  
  <p>So basically what I want to do is:</p>
  
  <ol>
  <li><p>For each user take the median of their values in the first column. I have written code (below) that works for this.</p></li>
  <li><p>If there are two equal "time" values in column 5 for each user then I want to average the values in column 4. So like for user <code>5406</code> the time values are both <code>7903</code>, I want to the average of values in column 4 - i.e. the average of <code>4</code> and <code>5</code> to end up with one value (<code>4.5</code>). </p></li>
  </ol>
  
  <p>But for example for the next user <code>5407</code> I will have two final values - one will be the average of 5 and 3 (because <code>7904</code> is repeated) and one will be 4 (because <code>7903</code> is not repeated). </p>
  
  <p>I am a bit confused about how to do this, I know there needs to be an <code>if</code> statement of some sort, but I've been stuck on it for ages. Can anyone help?</p>
  
  <p>Thanks</p>
  
  <p>Code for the first part:</p>
  
  <pre><code>u=unique(A(:,2));
  for i=1:size(u,1)
      M=find(A(i,2)==u(i));
      med(i)=median(A(M,1));
  end
  </code></pre>