Reputation: 81
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
Upvotes: 1
Views: 397
Reputation: 60504
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 (b-a)/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)
.
Upvotes: 5
Reputation: 15837
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]);
EDIT:
The 'ComparisonMethod'
option of function min is available starting from MATLAB R2021b. For older versions here is a way with dsearchn
:
[k, dst] = dsearchn(A(:), range(:));
result = A(k(1 + (diff(dst) < 0)));
EDIT2:
I packaged the second method as a function:
function out = near_range(A, range)
[k, dst] = dsearchn(A(:), range(:));
out = A(k(1 + (diff(dst) < 0)));
end
Usage:
rt(b, r, t) = near_range(audio_eventReshape(:, r, t), [audio_soundIntervals(b, r, t), audio_soundIntervals(b, r, t) + 1]);
Upvotes: 1