Home > custom > math > modal.m

modal

PURPOSE ^

function to find the most occuring element (modus/modal)

SYNOPSIS ^

function [m,n,in] = modal(A)

DESCRIPTION ^

 function to find the most occuring element (modus/modal)
 in a vector
 Usage: [m,in] = modal(A)
           where A is the array to analyse 
 Returns element m (modal), n (no of occurrences) and in (indices of m) in
 array A.
 Note: For matrices, use modal(A(:))
 Example: [m,n,in]=modal(round(rand(20,1)*10))

CROSS-REFERENCE INFORMATION ^

This function calls: This function is called by:

SOURCE CODE ^

0001 function [m,n,in] = modal(A)
0002 % function to find the most occuring element (modus/modal)
0003 % in a vector
0004 % Usage: [m,in] = modal(A)
0005 %           where A is the array to analyse
0006 % Returns element m (modal), n (no of occurrences) and in (indices of m) in
0007 % array A.
0008 % Note: For matrices, use modal(A(:))
0009 % Example: [m,n,in]=modal(round(rand(20,1)*10))
0010 
0011 % initialise output
0012 m=nan; 
0013 n=0; % holds the occurances of element m
0014 A(isnan(A))=[];
0015 i=1;
0016 while i<=length(A)    % loop over vector
0017    [s,l]=find(A==A(i)); % find first element
0018    s=sum(s);            % get occurances
0019         if s>n          % if it occurs more often than previous store
0020           n=s;          % the number of occurances
0021           m=A(i);       % the element that occured
0022           in=l;         % and the indices where it occured
0023         end
0024  A(A==A(i))=[];      % delete element occurances we just examine so its not counted again
0025  i=i+1;              % and proceed with the next element
0026 end
0027

Generated on Tue 24-Feb-2009 19:14:50 by m2html © 2003