[英]Find closest value to a constant in a multidimensional array in Matlab
I have a matrix B 我有一个矩阵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. 我想找到一个接近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. 因为我希望3是整个矩阵中最接近的值。 Any idea how I can do this?
知道我该怎么做吗?
Convert B
to a column (or row) vector and subtract the constant k
. 将
B
转换为列(或行)向量,然后减去常数k
。 k
may be greater or smaller than targeted value in B
, so use abs
to remove this problem. k
可能大于或小于B
目标值,因此请使用abs
消除此问题。 Now use min
to find the linear index of the closest value. 现在使用
min
查找最接近值的线性索引。 Then use ind2sub
to convert it into corresponding 3D subscripts r
, c
and v
. 然后使用
ind2sub
将其转换为相应的3D下标r
, c
和v
。
k = 2.9;
[~, ind] = min(abs(B(:)-k));
[r, c, v]= ind2sub(size(B), ind);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.