No BSD License  

Highlights from
Modal

1.0

1.0 | 2 ratings Rate this file 1 Download (last 30 days) File Size: 987 Bytes File ID: #15754

Modal

by Felix Hebeler

 

31 Jul 2007 (Updated 06 Aug 2007)

Calculates statistical mode and returns indices

| Watch this File

File Information
Description

Calculates the statistical mode (the most frequently occurring element) in a vector (or matrix), and returns the mode, the number of occurrences and the indices of the mode in the vector. Like the build in mode, only also includes indices.
Reasonable fast :-)
If more than one mode exist (2+ elements with equal maximum occurances) first one found is returned.

Plz comment or leave feedback

MATLAB release MATLAB 7.3 (R2006b)
Tags for This File  
Everyone's Tags
Tags I've Applied
Add New Tags Please login to tag files.
Comments and Ratings (6)
31 Jul 2007 Felix Hebeler

Just to make this clear: the build in 'mode' command does the trick in Matlab, this function only also works for 2&3D matrices and also returns the indices of the modal elements. If there are more than one element with equal number of occurrances, the first one found will be returned.

31 Jul 2007 Scott Miller

Felix

[m,in] = mode(A(:));

works for N dimensional matrices and with NaN, although the one-liner is much slower (there is a lot of general error checking overhead in mode) and doesn't return the number of hits. It also returns the first element found in index form, not subscript form.

If you use the A(:) trick in your code rather than reshape, modal runs 30% faster.

Scott

01 Aug 2007 Felix Hebeler

True, took this out of a script and didn't think about it. Thanks for the feedback, I kicked the reshape part out. It's even more than 30% faster in some cases now..

25 Nov 2009 Jan Churan  
25 Nov 2009 Jan Churan  
25 Nov 2009 Jan Churan

Beware, the function imho gives wrong results. It can be "fixed" by replacing 'sum' by 'length' in line 18 and '[]' by 'NaN' in line 24

Please login to add a comment or rating.
Updates
01 Aug 2007

Get rid of reshaping as suggested, speeds up modal 30% (thanks Scott)

01 Aug 2007

Get rid of the reshaping, speeds up modal 30% (thanks Scott)

06 Aug 2007

- Correct a bug where output was NaN if first cell in input grid are NaN and most cells in grid are NaN

Tag Activity for this File
Tag Applied By Date/Time
statistical mode Felix Hebeler 22 Oct 2008 09:21:17
indices Felix Hebeler 22 Oct 2008 09:21:17
modus Felix Hebeler 22 Oct 2008 09:21:17
modal Felix Hebeler 22 Oct 2008 09:21:17
probability Cristina McIntire 07 Nov 2008 11:49:21

Contact us at files@mathworks.com