Raul Stephan
Raul Stephan

Reputation: 25

Find an index position within a matrix

In this example I have a matrix (a)

a = 1       2       3       7
    0.9     0.6     0.2    0.2
    0.8     17      72     15

My goal is to search through the matrix a and find the index position of the highest value that is not >= 72. The matrix is just for illustration but I would like to know how to do this for a matrix of any dimension where rows and columns equal (2x2 3x3 4x4 ...)

in this case I would like to calculate the fact that the highest number within the constraints is

Rows=3 Cols = 2

Thanks

Upvotes: 2

Views: 4000

Answers (1)

tmpearce
tmpearce

Reputation: 12693

Step 1: determine the value you're interested in.

val = max(a(a<72));

Step 2: find the index of the element that corresponds to this value:

[r,c] = find(a==val,1,'first'); #%only take first element (this can be changed)
#r is the row index, c is the column index

You could also use linear indexing and ind2sub:

l = find(a==val); #%this time, find all elements that meet the criteria
[r,c] = ind2sub(size(a),l);

Here are links to documentation for find and ind2sub. You don't have to store the value (val) of interest either, you can just as easily put it all in one line.

Upvotes: 4

Related Questions