简体   繁体   中英

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. 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.

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. In your case this is 0.5.

Thus, finding the minimum of abs(A-0.5) will give you your answer. If A is a matrix, then A(:) is a vector you can apply your operation to. 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) .

You can use this function to find the nearest value of A to the range 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]);

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