2

Say we have an array named myMeasurements

int myMeasurements[9]={3,4,8,12,7,2,1,67,8};

How can I find the index of the maximum element of this array?

For example the MATLAB code would be:

myMeasurements = [3,4,8,12,7,2,1,67,8];
[maxValue,Index] = max(myMeasurements);

where maxValue is returned as 67 whereas the Index is returned as 8.

For the record, I am using Teensy 3.2 and I program it with the Arduino IDE using the Teensyduino add-on.

csg
  • 141
  • 1
  • 1
  • 6

4 Answers4

3

First of all, do you really need int values for the measurements or not? If not, and you have numbers between 0 and 255, switch the values to byte, your microcontroller will thank you.

Then, there is a problem with the other answers, which is... The variables cannot be left uninitialized!!! You can use this code to get the info you need:

(I also put the size of myMeasurements in a const variable.. You can thank me later for this)

const byte maxMeasurements = 9;
int myMeasurements[maxMeasurements ]={3,4,8,12,7,2,1,67,8};

byte maxIndex = 0;
int maxValue = myMeasurements[maxIndex];

for(byte i = 1; i < maxMeasurements; i++)
{
    if(myMeasurements[i] > maxValue) {
        maxValue = myMeasurements[i];
        maxIndex = i;
    }
}
frarugi87
  • 2,731
  • 12
  • 19
0
int myMeasurements[9] = {3,4,8,12,7,2,1,67,8};
int maxI = 0;
for(int i = 1;i < 9;i++) 
    if(myMeasurements[i] > myMeasurements[maxI])
       maxI = i;
A. L. K.
  • 49
  • 6
-1

Arduino forum has discussed finding the index once you know which value's index you want. Solution was arrived at by traversing the array by value you were looking for.
For your requirement, you will have to
(1) find the maxValue first and then
(2) find the position(index) of that maxValue using the code they have discussed here : https://forum.arduino.cc/index.php?topic=121116.0

-1

The code given by Jakub Krnáč gets a slight change which will give the index of the max value. Here is the changed code:

int myMeasurements[9]={3,4,8,12,7,2,1,67,8};
int max,current, maxI; 
for(int i = 0;i < 9;i++){
    current = myMeasurements[i];
    if(current > max){
        max = current;
        maxI = i;
    }
}
Faiq Irfan
  • 129
  • 1
  • 7