0

I'm working on kmeans clustering algorithm, and I need to find the index of the smallest value in the array.

For example, I wrote this code for 3 item:

if ((DistanceArray[1, j] < DistanceArray[2, j]) && 
    (DistanceArray[1, j] < DistanceArray[3, j]))
{
    min= 1;
} 
else if (DistanceArray[2, j] < DistanceArray[3, j])
{
    min= 2;
}
else
{
    min= 3;
} 

But I need to retrieve minimum value from a multidimensional array.

How can do this?

2 Answers 2

1

Iterate over each value and compare it to the current minimum. Declare min as float.MaxValue so any number except the max value for a float will be less than it.

float min = float.MaxValue; //set 'min' to the maximum value of a float
int minI, minJ;  //use if you want to track indices of the min value

for (int i = 0; i <= DistanceArray.GetUpperBound(0); i++)
{
    for (int j = 0; j <= DistanceArray.GetUpperBound(1); i++)
    {
        if (DistanceArray[i, j] <= min) //changed to '<= min' to which means if
        {                               //there are multiple minimum values the
            min = DistanceArray[i, j];  //one with the higher indices will be used
            minI = i;
            minJ = j;
        }
    }
}
Sign up to request clarification or add additional context in comments.

16 Comments

Why do you do < (DistanceArray.GetUpperBound(0) + 1) when you could just do <= DistanceArray.GetUpperBound(0)?
Don't initialize min so it's null ????? int is a value type,it cannot be null,it will have a default value 0
min isn't nullable in this context. Either make it int? min = null; or int min = int.Minvalue; and remove the null check in the inner loop.
I would avoid using null with min. Just do int min = Int32.MaxValue and change if (min == null || ... to if (...
Give @Matthew some upvotes for maintaining this snippet.
|
0

Try this,Here arr is two dimensional array

   int? minValue = null;
   var i = 0;
   var j = 0;
    foreach (var m in arr)
    {
      var min1 =   m.Min();
      if (minValue == null || minValue > min1)
      {
          minValue = min1;
          i = m.ToList().IndexOf(min1);
          j = arr.ToList().IndexOf(m);
      }

    }

1 Comment

yeah I know,but nested foreach is more extremely inefficient to me

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.