MATLAB: Finding nearest low match in array

closestnearest

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.

Best Answer

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)