Search code examples
arraysmatlabfindclosest

Find closest value to a constant in a multidimensional array in Matlab


I have a matrix B

B(:,:,1) =

         2     8
         0     5

B(:,:,2) =

         1     3
         7     9 

I want to find the index of a value close e.g. to 2.9. I tried the following code:

[r,c,v] = ind2sub(size(B),find(min(abs(B-2.9))));

I get:

r =

     1
     2
     1
     2  
 c =

     1
     1
     2
     2  
 v =

     1
     1
     1
     1

What I want is:

r = 1  
c = 2  
v = 2

because I expect 3 to be the nearest value in the entire matrix. Any idea how I can do this?


Solution

  • Convert B to a column (or row) vector and subtract the constant k. k may be greater or smaller than targeted value in B, so use abs to remove this problem. Now use min to find the linear index of the closest value. Then use ind2sub to convert it into corresponding 3D subscripts r, c and v.

    k = 2.9;
    [~, ind] = min(abs(B(:)-k));
    [r, c, v]= ind2sub(size(B), ind);