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.
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.