简体   繁体   中英

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 eg 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?

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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM