Find the closest value in a matrix matlab

user3366536 picture user3366536 · Mar 24, 2014 · Viewed 10.9k times · Source

How can I find the closest element in a matrix in matlab?

Suppose I have a matrix of the size 300x200 and I want to find the value and the index of the element in the matrix which is the closest to a element given.

Does anyone know how this can be done in matlab? I know how to do this for a given array but I can not figure out how this is done for a matrix.

Answer

Luis Mendo picture Luis Mendo · Mar 24, 2014

Let matrix denote your matrix, and ref denote the reference value you want to get closest to. Then you can use

[value, ii] = min(abs(matrix(:)-ref));    %// linear index of closest entry
[row, col] = ind2sub(size(matrix), ii);   %// convert linear index to row and col

value gives the value of the closest entry; and row, col give its row and column indices.