2

I have 72x7 double called P like this:

1 45 2  61 7 1 11  
1 32 6  23 64 1 32  
2 55 32 25 90 3 24  
2 45 6  6 16 3 1  
2 45 4  17 20 3 1  
...
3 87 24 43 71 3 41  
5 64 8  66 75 98 1  

Two columns I'm interested in are 1 and 6. Let's call a value in column 1 m and a value in column 6 n. m ranges from 1-6 and n ranges from 1 to either 3 or 4. I would like to count how many rows that has a specific combination of m and n. Let's call this value x. For instance, in this example if m=1 and n=1, x would be 2 since there are two rows where m=1 AND n=1 (row 1 and 2). If m=2 AND n=3, x would be 3 (row 3, 4, and 5). I intend to do a loop, something like this:

for m=1:6
   for n=1:a % a could be either 3 or 4
   x = (operation done here)
   end
end

I tried both numel and unique functions but neither gave me the right answer. Could someone help me?

Thanks,

Alex

2 Answers 2

5

One approach -

%// Get columns 1 and 6 from input matrix, P
P16 = P(:,[1 6])

%// Get unique row combinations and their IDs
[unqrows,~,idx] = unique(P16,'rows')

%// Get the counts for each combination
counts = accumarray(idx(:),1) %// Or histc(idx,1:max(idx))

%// Present the output
out = [unqrows counts]

Thus, with P as -

P = [1 45 2  61 7 1 11
    1 32 6  23 64 1 32
    2 55 32 25 90 3 24
    2 45 6  6 16 3 1
    2 45 4  17 20 3 1 ]

we would have the output as -

out =
     1     1     2
     2     3     3

So, in the output, the first column represents m, the second one would be n and the final column would be the expected counts.

4
  • I was about to write a solution.... and this is pretty much what I would have done. Bah lol. +1.
    – rayryeng
    Apr 10, 2015 at 18:03
  • @rayryeng I am sorry, as it turns out accumarray is fun too! :)
    – Divakar
    Apr 10, 2015 at 18:04
  • It's one of my favourite functions to use in MATLAB! Some of my favourite answers use it :)
    – rayryeng
    Apr 10, 2015 at 18:06
  • Nice! As usual, there's a similar approach based on sparse and find (instead of accumarray and unique)
    – Luis Mendo
    Apr 10, 2015 at 19:24
5

Assuming positive integer values, this uses sparse to produce the desired result. The output format is as in Divakar's answer:

[ii, jj, kk] = find(sparse(P(:,1), P(:,6), 1));
result = [ii jj kk];
2
  • 1
    Nice! Interesting, we are seeing lots of these kinds recently on SO.
    – Divakar
    Apr 10, 2015 at 19:49
  • @Divakar Certainly! I had a deja vu feeling while answering this :-)
    – Luis Mendo
    Apr 10, 2015 at 20:50

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.