Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 567
Ash Avatar asked Jan 08 '23 18:01

Ash


2 Answers

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,

like image 65
Ratbert Avatar answered Jan 14 '23 03:01

Ratbert


One approach -

%// Calculate all indices of the grid created with those two X-Y conditions
idx = bsxfun(@plus,(find(Y==3)-1)*size(Z,1),find((X>1 & X<4)).') %//'

%// Get the index corresponding to minimum from that grided Z
[~,min_idx] = min(Z(idx(:)))

%// Get corresponding X-Y indices by using indices calculated earlier
[indX,indY] = ind2sub([numel(X) numel(Y)],idx(min_idx))
like image 24
Divakar Avatar answered Jan 14 '23 04:01

Divakar