Search code examples
matlabmatrixfindmatrix-indexing

Finding index of element matching condition of matrix - Matlab


Given a matrix Z(i,j) such that it maps to two arrays X(i), and Y(j). I am trying to find elements of Z (and hence the corresponding X and Y) within a certain range.

I am now doing the following using logical indexing. Given this example

 X = 1:5;
 Y = 1:5;
 Z =    [17    24     1     8    15
         23     5     6    14    16
          4     6    13    20    22
         10    12    19    21     3
         11    18    25     2     9]
 Z((X>1 & X<4),Y==3)

This works fine, but now I wish to find the minimum of the returned values from this particular range,

Which I do with

min(Z((X>1 & X<4),Y==3))

But now how I get back the corresponding X and Y values of the minimum? Since my logical indexing returns an array, all methods I have tried so far returns the index of the min in the answer array, not the original Z matrix.

I can't use

[row col] = find(Z==min(Z((X>1 & X<4),Y==3)))

Because of the repeats. What are my alternatives?


Solution

  • To retrieve the original indices, you have to keep the memory of the indices of your two conditions on x and y (which I put in the arrays cX and cY) and then use the function ind2sub.

    NB: your code is a little bit confusing since x stands for the lines and y for the columns, but I have kept the same convention in my answer.

    In practice, this gives:

    % --- Definition
    X = 1:5;
    Y = 1:5;
    Z =    [17    24     1     8    15
            23     5     6    14    16
             4     6    13    20    22
            10    12    19    21     3
            11    18    25     2     9];
    
    % --- Get the values of interest
    cX = find(X>1 & X<4);
    cY = find(Y==3);
    v = Z(cX,cY);
    
    % --- Get position of the minimum in the initial array
    [~, I] = min(v(:));
    [Ix, Iy] = ind2sub([numel(cX) numel(cY)], I);
    
    i = cX(Ix);      % i = 2
    j = cY(Iy);      % j = 3
    

    Best,