简体   繁体   English

如何找到最接近 MATLAB 范围的矩阵元素值?

[英]How can I find the nearest matrix element value to a range in MATLAB?

I have a 3D matrix and I need to find the nearest value to [0 to 1] range.我有一个3D 矩阵,我需要找到最接近 [0 到 1] 范围的值。 For example, I have [-2.3 -1.87 -0.021 1.1 1.54] and -0.021 should be selected as it is the nearest value to the range.例如,我有 [-2.3 -1.87 -0.021 1.1 1.54] 并且应该选择 -0.021,因为它是最接近该范围的值。

EDITED: There would be zero or one value within the range.编辑:范围内将有零或一个值。 If there is one, that should be returned and if there is nothing, the nearest value should be returned如果有一个,应该返回,如果没有,应该返回最接近的值

EDITED: This is the part of code which I'm trying to work correctly:编辑:这是我试图正常工作的代码部分:

rt = zeros(size(audio_soundIntervals, 1), size(prtcpnt.audioAttention_ToM.sound_eventTime, 1), size(prtcpnt.audioAttention_ToM.sound_eventTime, 2));

for r = 1:size(prtcpnt.audioAttention_ToM.sound_eventTime, 1)
    for t = 1:size(prtcpnt.audioAttention_ToM.sound_eventTime, 2)
        for b = 1:size(audio_soundIntervals, 1)
       % here, I want to find the nearest element of audio_eventReshape(:, r, t) to the range [audio_soundIntervals(b, r, t), audio_soundIntervals(b, r, t) + 1]
        end
    end
end

The value nearest the center of the range is always the one you are looking for.最接近范围中心的值始终是您要查找的值。 I suggest you try out a few examples on paper to convince yourself of this.我建议你在纸上尝试一些例子来说服自己。

The center of the range [a,b] is (ba)/2.范围 [a,b] 的中心是 (ba)/2。 In your case this is 0.5.在您的情况下,这是 0.5。

Thus, finding the minimum of abs(A-0.5) will give you your answer.因此,找到abs(A-0.5)的最小值将为您提供答案。 If A is a matrix, then A(:) is a vector you can apply your operation to.如果A是一个矩阵,那么A(:)是一个可以应用你的操作的向量。 So we have:所以我们有:

[~,indx] = min(abs(A(:)-0.5));

Or more generally:或更一般地说:

[~,indx] = min(abs(A(:)-(b-a)/2));

indx is the linear index into A for the element you are looking for, get the value with A(indx) . indx是您要查找的元素在A中的线性索引,使用A(indx)获取值。

You can use this function to find the nearest value of A to the range range :您可以使用此 function 来找到A与范围range最近的值:

function out = near_range(A, range)
  [m1, idx1] = min(A - range(1), [], 'all', 'ComparisonMethod', 'abs');
  if abs(m1) >= diff(range)
    out = A(idx1);
    return
  end
  [m2, idx2] = min(A - range(2), [], 'all', 'ComparisonMethod', 'abs');
  if abs(m1) < abs(m2)
    out = A(idx1);
  else
    out = A(idx2);
  end
end

Usage:用法:

result =  near_range([-2.3 -1.87 -0.021 1.1 1.54], [0 1]);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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