How to get MATLAB to display the index of the minimum value in a 2D array?

后端 未结 5 2006
余生分开走
余生分开走 2020-12-28 17:21

I\'m trying to write a script in MATLAB that finds the location of the minimum value of a 2D array of numbers. I am certain there is only 1 minimum in this array, so having

相关标签:
5条回答
  • 2020-12-28 17:33

    As an alternative version, combine min to get the minimum value and find to return the index, if you've already calculated the minimum then just use find.

    >> a=magic(30);
    >> [r,c]=find(a==min(min(a)))
    
    r =
         1
    c =
         8
    

    Or depending on how you want to use the location information you may want to define it with a logical array instead, in which case logical addressing can be used to give you a truth table.

    >> a=magic(30);
    >> locn=(a==min(min(a)));
    
    0 讨论(0)
  • 2020-12-28 17:36

    An alternate solution using an inline function will work.

        >> min_index = @(matrix) find(matrix == min(reshape(matrix, [1,numel(matrix)])));
    
        >> a=magic(30);
        >> [r,c]=min_index(a)
    
        r =
             1
    
        c =
             8
    
    0 讨论(0)
  • 2020-12-28 17:53

    Look at the description of the min function. It can return the minimum value as well as the index. For a two dimensional array, just call it twice.

    A = rand(30); % some matrix
    [minColVal, minColIdx] = min(A);
    [minRowVal, minRowIdx] = min(minColVal);
    
    minVal = minRowVal;
    minValIdx = [minColIdx(minRowIdx), minRowIdx];
    

    Edit: @b3's solution is probably computationally more elegant (faster and needs less temporary space)

    0 讨论(0)
  • 2020-12-28 17:56

    To find min or max in a subset of a vector - If A is a vector and "lowerBound" and "upperBound" are the bounds of the vector among which you need to find the max (or min) value, then use this command -

    [Value,Index]=min(A(lowerBound:upperBound));
    

    This returns "Value" as the min or max value among A(lowerBound) and A(uppedBound) and "Index" as with "lowerBound" as the offset. So to find the absolute index, you need to add "lowerBound" to the Index.

    0 讨论(0)
  • 2020-12-28 17:57

    You could reshape the matrix to a vector, find the index of the minimum using MIN and then convert this linear index into a matrix index:

    >> x = randi(5, 5)
    
    x =
    
         5     4     4     2     4
         4     2     4     5     5
         3     1     3     4     3
         3     4     2     5     1
         2     4     5     3     5
    
    >> [value, index] = min(reshape(x, numel(x), 1));
    >> [i,j] = ind2sub(size(x), index)
    
    i =
    
         3
    
    
    j =
    
         2
    
    0 讨论(0)
提交回复
热议问题