How can I calculate the statistical mode from a set of values obtained from a distance sensor in an Arduino programme?
First, two caveats: (a) The question is fairly general and might be better asked on stackoverflow, except that asking here will tend to focus answers on algorithms with low memory requirements or online methods (methods that continually compute an answer as data streams through). (b) In many cases – eg, with noisy sensors, noisy inputs, changing inputs – the statistical mode is less likely to be relevant than the statistical mean or median. What computation method is best depends on which model of Arduino you use (because available RAM depends on model), what range of data your distance sensor returns, how many readings are taken, what you want to do with the data, whether an approximate (or nearly-correct) answer is acceptable vs an exact answer, and so forth. Assuming you take 30 readings and store the data in an array d (that is, in d[0] ... d[29]), you could act as follows:
You could make this more elaborate by detecting whether hiv is already equal to d[i] and testing ni ≥ hic rather than ni > hic. This would allow detecting cases where two values are modal. The method suggested in a comment – counting number of readings in various intervals – may compute an incorrect answer because the interval with the highest total count need not be the interval the mode is in. |
|||
|
if ... else if ...
statements. If this is not what you meant, then explain it better... – frarugi87 Jan 18 '16 at 16:39if
statements. At the end iterate over all the frequency classes to find the maximum value – frarugi87 Jan 18 '16 at 17:00