1

Given a vector v = [2 2] I am trying to find how many times it is present in a matrix, say

data_2 =

 2     2
 2     2
 1     2
 2     2
 2     1
 1     2
 2     1
 1     1
 2     2
 2     2

In the above dummy example, [2 2] occurs in 5 rows out of total 10 rows present. The following code should ideally be giving me the same answer -

numel(find(data_2 == repmat(v,size(data_2,1),1)))

However the answer for the above is 14. Logically I am trying to simply count occurrences, but I must have messed up with the MATLAB commands. Any help would be appreciated.

AruniRC
  • 5,070
  • 7
  • 43
  • 73

1 Answers1

1

Use bsxfun, then all row-wise, then sum:

sum(all(bsxfun(@eq, v, data_2),2))

Or use ismember with the 'rows' option and then sum:

sum(ismember(data_2,v,'rows'))

Your approach is similar to my first solution (bsxfun is essentially an implicit, faster repmat; see here or here). The problem with your code is that it counts each column separately. A row-wise all is needed to combine the results of all columns into a single result per row:

numel(find(all((data_2 == repmat(v,size(data_2,1),1)),2)))

or better use sum(...) instead of numel(find(...)):

sum(all((data_2 == repmat(v,size(data_2,1),1)),2))
Community
  • 1
  • 1
Luis Mendo
  • 110,752
  • 13
  • 76
  • 147
  • Thanks. I figured out the element-wise comparison instead of row-wise. Ending up using `ismember` - more intuitive. – AruniRC Jan 31 '14 at 22:19