Search code examples
matlabmatrixclosest

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.


Solution

  • 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