Mode

samjesse

Active Trader
Aug 30, 2011
118
0
27
Hi

I searched the docs. for no avail. Is there a function which returns the mode, i.e. the value that occurs most frequently in an array?

thx
 

Enivid

Administrator
Staff member
Nov 30, 2008
18,607
1,366
144
Odesa
www.earnforex.com
I don't know such function, but it can be coded:

MQL5:
// Returns the value of the mode of the array a
//  a - array
//  n - size
int mode(const int &a[], uint n)
{
	uint frequency[];
	int index[];
	bool found;
	uint k = 0; // Index for index array
 
	ArrayResize(frequency, n);
	ArrayResize(index, n);
	ArrayInitialize(frequency, 0);
	ArrayInitialize(index, 0);
	// Cycle through initial array
	for (uint i = 0; i < n; i++)
	{
		// Find the current element in the index array
		found = false;
		for (uint j = 0; j <= i; j++)
		{
			if (index[j] == a[i])
			{
				frequency[j]++;
				found = true;
				break;
			}
		}
		// If the element wasn't found in the index array, add it to the index array
		if (!found)
		{
			index[k] = a[i];
			frequency[k] = 1;
			k++;
		}
	}
 
	return index[ArrayMaximum(frequency)];
}

Probably not the optimal way of doing it, but it works. Please let me know if you find a bug or if you find a better solution.
 
Last edited: