Finding nearest low match in array
Show older comments
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.
Accepted Answer
More Answers (3)
Kuifeng
on 4 Apr 2016
bigger_value_location = find((f-val)>0);
nearest = f(bigger_value_location(1)-1)
3 Comments
Kuifeng
on 4 Apr 2016
you are welcome. pls accept this answer if it's ok. Note (1) f values need to be sorted from small to big
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);
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
on 4 Apr 2016
f= [1:0.5:5]
val = 2.3
[ii,jj]=sort(f)
ii1=find(ii>val,1)-1
idx=jj(ii1)
Categories
Find more on Logical in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!