MATLAB: Find next value above threshold

find nextsort

Hello,
I have a large volume of data, and i need to find the next value above a threshold but within a range of values.
ie
Data range 300000 to 340000 (the corresponding values will drop off in the middle and increase either side of centre, centre = 320000)
i need to set a datum point of 320000 (middle) then i need to find the closest value to the centre that is greater than >1500
Im fairly new to matlab, so sorry if this is begineers question, i cant seem to find relavant links
Thank you
Joe

Best Answer

Try this.
% First make sample data because Joe forgot to give us his actual data.
period = 20000;
x = linspace(22000, 42000, 800);
y = 3000 * (0.5 + cos(2 * pi * (x - 32000) / period));
% Add some noise
y = y + 800 * rand(1, length(y));
plot(x, y, 'b-');
grid on;
xlabel('x', 'FontSize', 15);
ylabel('y', 'FontSize', 15);
% Now we have our sample x,y data and we can begin:
% Find max of y - it should be at an x value of around 32,000.
[yMax, indexOfMax] = max(y);
% Draw vertical red line there
hold on;
line([x(indexOfMax), x(indexOfMax)], [min(y), y(indexOfMax)], 'Color', 'r', 'LineWidth', 2);
% Also draw red line across the threshold of 1500
line(xlim, [1500, 1500], 'Color', 'r', 'LineWidth', 2);
% Find logical indexes for indexes where y is less than 1500
logicalIndexes = y < 1500;
% Find linear indexes:
linearIndexes = find(logicalIndexes);
% Note: the above two lines could be done in one line
% but I wanted to demo both linear and logical indexes for you.
% Find distances of all indexes where y<1500 to the index of the max y.
indexDistances = abs(linearIndexes - indexOfMax);
% Find out which index is closest to indexOfMax
[indexDistance, indexOfThreshold] = min(indexDistances)
% Draw red line there, at the closest threshold.
hold on;
line([x(indexOfThreshold), x(indexOfThreshold)], [min(y), y(indexOfThreshold)], 'Color', 'r', 'LineWidth', 2);
0001 Screenshot.png
The index of the point you want is indexOfThreshold, and the x value is x(indexOfThreshold) and the y value is y(indexOfThreshold).
You can see in this example, that the closest point to the max where the data first goes above 1500 is 26500.
Related Question