Finding nearest low match in array

조회 수: 45 (최근 30일)
Sac
Sac 2016년 4월 4일
댓글: Kuifeng 2016년 4월 4일
Hello, I’m trying to find the nearest match of a value in an array, with the condition that it never rounds up. To explain what I mean, imagine a vector of
f= [1:0.5:5]
where I want to find the nearest low match of 2.3. To simply find the nearest match, I would use
val = 2.3
tmp = abs(f-val)
[i i] = min(tmp)
nearest = f(idx)
How do I reformulate this so it gives me the index of 2 instead? Any tips?
Note, I want it to handle exact matches and negative values as well.

채택된 답변

Image Analyst
Image Analyst 2016년 4월 4일
There may be a more compact way of doing it but I'm doing it in explicit separate steps with a ton of comments so that you can easily understand it:
% Define target value.
targetValue = 2.3
% Define test values. This is just for demo, you'd use your actual values.
testValues = 5 * rand(1, 10)
% Find differences
diffValues = testValues - targetValue
% We only want values less than the target value
% so those diffValues will be negative.
% We want the max of those, so set the others to -inf
diffValues(diffValues > 0) = -inf;
% Now we can find the index of the greatest value that
% is still less than the reference value.
[~, indexOfMax] = max(diffValues)
% Get the value from the testValues array
maxValue = testValues(indexOfMax)

추가 답변 (3개)

Kuifeng
Kuifeng 2016년 4월 4일
bigger_value_location = find((f-val)>0);
nearest = f(bigger_value_location(1)-1)
  댓글 수: 3
Kuifeng
Kuifeng 2016년 4월 4일
you are welcome. pls accept this answer if it's ok. Note (1) f values need to be sorted from small to big
Guillaume
Guillaume 2016년 4월 4일
편집: Guillaume 2016년 4월 4일
This answer only works because the nearest value happens to be the first value above the search value. It would fail with
f = fliplr(1:0.5:5);

댓글을 달려면 로그인하십시오.


Guillaume
Guillaume 2016년 4월 4일
편집: Guillaume 2016년 4월 4일
A simple way would be to set any value below 0 in your tmp to Inf, before calling min:
f = [1 1.5 2.5 3 2 4.5 5.5 5]; %shuffled values to show that ordering does not matter
val = 2.3;
tmp = val - f;
tmp(tmp < 0) = Inf;
[~, loc] = min(tmp)

Azzi Abdelmalek
Azzi Abdelmalek 2016년 4월 4일
f= [1:0.5:5]
val = 2.3
[ii,jj]=sort(f)
ii1=find(ii>val,1)-1
idx=jj(ii1)

카테고리

Help CenterFile Exchange에서 Logical에 대해 자세히 알아보기

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by