Home > utility > rowCount.m

rowCount

PURPOSE ^

rowCount: Unique element counts for a given matrix.

SYNOPSIS ^

function [uniq_row, count] = rowCount(A)

DESCRIPTION ^

 rowCount: Unique element counts for a given matrix.
    [uniq_row, count] = rowCount(A)
    A: input matrix where each row is viewed as an "element"
    uniq_row: sorted listing of unique row in A
    count: counts for each returned unique row

    If A is a cell array of strings, then the output uniq_row is also a
    cell array of strings.

    Roger Jang, 19981125, 20071205

CROSS-REFERENCE INFORMATION ^

This function calls: This function is called by:

SUBFUNCTIONS ^

SOURCE CODE ^

0001 function [uniq_row, count] = rowCount(A)
0002 % rowCount: Unique element counts for a given matrix.
0003 %    [uniq_row, count] = rowCount(A)
0004 %    A: input matrix where each row is viewed as an "element"
0005 %    uniq_row: sorted listing of unique row in A
0006 %    count: counts for each returned unique row
0007 %
0008 %    If A is a cell array of strings, then the output uniq_row is also a
0009 %    cell array of strings.
0010 %
0011 %    Roger Jang, 19981125, 20071205
0012 
0013 if nargin<1, selfdemo; return, end
0014 if isempty(A), uniq_row=[]; count=[]; return; end
0015 
0016 cellstr_input = 0;
0017 if iscellstr(A),
0018     A = char(A);
0019     cellstr_input = 1;
0020 end
0021 term = sortrows(A);
0022 tmp1 = term;
0023 tmp1(end+1, :) = tmp1(end, :) + 1;
0024 tmp2 = tmp1(1:end-1, :) - tmp1(2:end, :);
0025 index = find(sum(abs(tmp2), 2) ~= 0);
0026 uniq_row = term(index, :);
0027 count = diff([0; index]);
0028 
0029 % Rearrange according to decending order of counts
0030 %[count, index] = sort(count);
0031 %count = flipud(count);
0032 %index = flipud(index);
0033 %uniq_row = uniq_row(index, :);
0034 
0035 % Return cell array of string if given cell array of string
0036 if cellstr_input,
0037     uniq_row = cellstr(uniq_row);
0038 end
0039 
0040 % ========== Subfunction ==========
0041 function selfdemo
0042 A = [    '一台';...
0043     '八爪'; ...
0044     '三光'; ...
0045     '人性'; ...
0046     '八爪'; ...
0047     '三光'; ...
0048     '八爪'];
0049 fprintf('Original string matrix:\n');
0050 disp(A);
0051 fprintf('After sorting and finding counts of unique rows:\n');
0052 [uniq_row, count] = feval(mfilename, A);
0053 for i = 1:length(count),
0054     fprintf('%s ==> %g\n', uniq_row(i, :), count(i));
0055 end
0056 fprintf('Original cell array of strings:\n');
0057 A = {'abc';'acd';'ad';'a';'bc';'ad';'acd';'acd'}; 
0058 disp(A);
0059 [uniq_row, count] = feval(mfilename, A);
0060 fprintf('After sorting and finding counts of unique rows:\n');
0061 for i = 1:length(count),
0062     fprintf('%s ==> %g\n', uniq_row{i}, count(i));
0063 end

Generated on Tue 01-Jun-2010 09:50:34 by m2html © 2003