Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find the closest value in a matrix matlab

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.

like image 509
user3366536 Avatar asked Dec 01 '22 16:12

user3366536


2 Answers

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.

like image 110
Luis Mendo Avatar answered Dec 10 '22 12:12

Luis Mendo


A smaller case might help you understand -

Code

%%// Given big matrix, taken as a matrix of random numbers for demo
a1 = rand(10,5); %%// Replace this with your 300X200 matrix

%// For demo, let us assume, you are looking for the element that happens to be closest to the element in the 4th row and 5th column, which will be verified at the end 
element = a1(4,5)+0.00001; %%// The element in search

%%// Find the linear index of the location
[~,ind] = min(reshape(abs(bsxfun(@minus,a1,element)),numel(a1),[]));

%%// Convert the linear index into row and column numbers
[x,y] = ind2sub(size(a1),ind) 

Output

x =
     4

y =  
     5

As can be seen, the output matches the expected answer.

Extended Part: If you have a set of search numbers, you can process them for closeness very efficiently using bsxfun. This is shown below -

Code

%%// Given big matrix, taken as a matrix of random numbers for demo
a1 = rand(10,5); %%// Replace this with your 300X200 matrix

%// For an array of search numbers
search_array = [a1(4,5)+0.00001;a1(6,5)+0.00001;a1(4,4)+0.00001;a1(4,2)+0.00001];

%%// Find the linear index of the location
[~,ind] = min(abs(bsxfun(@minus,a1(:),search_array')));%//'

%%// Convert the linear index into row and column numbers
[x,y] = ind2sub(size(a1),ind) 

Output

x =
     4     6     4     4


y =
     5     5     4     2
like image 28
Divakar Avatar answered Dec 10 '22 10:12

Divakar