File Exchange Pick of the Week

Our best user submissions

Counting Elements

Jiro's pick this week is COUNTMEMBER by Jos.

A while back, I wrote a Pick of the Week post on a file that created a MATLAB file template. In that post, I talked a bit about a "best practice" for formatting your MATLAB files: things like, having an H1 line, including help text, including examples, etc.

How is that related to this week's pick? Well, I chose countmember because Jos writes very well-written files. (I could have chosen some of his other files, but I liked the code also.) Open the file up and see it for yourself. He has a simple, but descriptive H1 line so that LOOKFOR will be able to find it. The help block follows the format that many MathWorks MATLAB files use: capitalized syntax (but case-sensitive example code), the examples can be directly executed (highlight and F9), and he has a "See also" section for related functions.

help countmember
  COUNTMEMBER - count members
    C = COUNTMEMBER(A,B) counts the number of times the elements of A occurs
    in B, such the Ci = sum(B==Ai). C has the same size and shape as A.
    A may contain non-unique elements. A and B should be of the same type. 
    A can be be a cell array.
      countmember([1 2 1 3],[1 2 2 2 2]) 
         -> 1     4     1     0
         -> 2     0     0
    2005 Jos van der Geest

Of course, the other reason I selected this was his elegant solution to the task of counting the occurrence of elements. The code has a nice error checking mechanism and deals with empty input arguments. The code is vectorized (no for-loops) and uses UNIQUE to eliminate redundant search. Also, notice the little trick to reduce overhead in his lines of code for UNIQUE and ISMEMBER.


We will be taking next Friday off for holiday, but we'll be back next year on the 2nd of January. Have a safe and happy holiday!

Published with MATLAB® 7.7



To leave a comment, please click here to sign in to your MathWorks Account or create a new one.