Option 5: arrayfun
counts5 = arrayfun( @(x)sum(M==x), unique(M) );
M = [1; 2; 6; 2; 6]; counts5 = arrayfun( @(x)sum(M==x), unique(M) ) counts5 = 1 2 2
Option 6: bsxfun
counts6 = sum( bsxfun(@eq, M, unique(M)') )';
The function “bsxfun” applies element-by-element binary operation to two arrays. Though this method is not hard, but it is easier to understand if we do it step by step.
M = [1; 2; 6; 2; 6]; unique(M)' ans = 1 2 6 bsxfun(@eq, M, unique(M)') ans = 1 0 0 0 1 0 0 0 1 0 1 0 0 0 1 counts6 = sum( bsxfun(@eq, M, unique(M)') )' counts6 = 1 2 2
Option 7: sparse
counts7 = full(sparse(M,1,1));
Again, for this approach, we need to check the MATLAB help file first. “S = sparse(i,j,s,m,n,nzmax) uses vectors i, j, and s to generate an m-by-n sparse matrix such that S(i(k),j(k)) = s(k), with space allocated for nzmax nonzeros. Vectors i, j, and s are all the same length. Any elements of s that are zero are ignored, along with the corresponding values of i and j. Any elements of s that have duplicate values of i and j are added together.” An example is given below.
sparse(M,1,1) ans = (1,1) 1 (2,1) 2 (6,1) 2 counts7 = full(sparse(M,1,1)) counts7 = 1 2 0 0 0 2
Part 1: http://nw360.blogspot.com.au/2013/06/count-number-of-elements-in-vector-or.html
Part 2: http://nw360.blogspot.com.au/2013/06/count-number-of-elements-in-vector-or_20.html
Part 3: http://nw360.blogspot.com.au/2013/06/count-number-of-elements-in-vector-or_21.html
References:
1 MATLAB help file.
2 http://stackoverflow.com/questions/2880933/how-can-i-count-the-number-of-elements-of-a-given-value-in-a-matrix
No comments:
Post a Comment