Help with array max position

Hi everyone,
I have a question please

If I have an array of 12 variables and I found the max by the code
how can I fine the position of the max variable in the array ?

for example if the value of v5 was the max, what is the code to show that the position v5 (which is position 4 in the array) holds the max variable ?

and thank you

example code:

float v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12;
float V[12] = { v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12 };

float V_max = maximum(V,12);



float maximum(float *data,int count)
{
 int l;
 float maxval;
 maxval = 1.175494351e-38f;
 for(l=0; l<=count; l++)
 {
   if(data[l] > maxval)
   {
     maxval = data[l];
   }
 }
 return maxval;
}

in the same way that you are saving the maximum value to a variable to remember it, save the loop index to a variable to give you the index for the max number.

void setup(){}
void loop(){}

float v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12;
float V[12] = { v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12 };

int maxPosition=12;  
float V_max = maximum(V, &maxPosition);
//maxPosition now hold the position of V_max
//OR -1 if no value greater than 1.175494351e-38f was found

float maximum(float *data,int* count)
{
 int l;
 int maxPos=-1;
 float maxval;
 maxval = 1.175494351e-38f;
 for(l=0; l<= *count; l++)
 {
   if(data[l] > maxval)
   {
     maxval = data[l];
     maxPos=l;
   }
 }
 *count=maxPos;
 return maxval;
}

KenF: shouldn’t this:

 for(l=0; l<= *count; l++)

actually be this:

 for(l=0; l < *count; l++)

That is, if there are 12 elements, only 0-11 are valid. Also, you could improve the flexibility of the code with two minor changes:

float V[] = { v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12 };

int maxPosition= sizeof(V) / sizeof(V[0]);

Now you could add more float variables to the list without having to edit the array code size.

econjack:
KenF: shouldn’t this:

 for(l=0; l<= *count; l++)

actually be this:

 for(l=0; l < *count; l++)

That is, if there are 12 elements, only 0-11 are valid. Also, you could improve the flexibility of the code with two minor changes:

Yes. it’s an artifact of the copy and paste I did from the original code.

float V[] = { v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12 };

int maxPosition= sizeof(V) / sizeof(V[0]);




Now you could add more float variables to the list without having to edit the array code size.

Much better implementation.