As shown by the solid and dashed line, I\'d like to create a function where I set a threshold for y (Intensity) from that threshold it gives me corresponding x value (d
No while
loop is needed here... You can do this with logical indexing for the threshold condition and find
to get the first index:
% Start with some x and y data
% x = ...
% y = ...
% Get the first index where 'y' is greater than some threshold
thresh = 10;
idx = find( y >= thresh, 1 ); % Find 1st index where y >= thresh
% Get the x value at this index
xDesired = x( idx );
Note that xDesired
will be empty if there was no y
value over the threshold.
Alternatively, you already have a polynomial fit, so you could use fzero
to get the x
value on that polynomial for a given y
(in this case your threshold).
% x = ...
% y = ...
thresh = 10;
p = polyfit( x, y, 3 ); % create polynomial fit
% Use fzero to get the root of y = a*x^n + b*x^(n-1) + ... + z when y = thresh
xDesired = fzero( @(x) polyval(p,x) - thresh, x(1) )
Note, this method may give unexpected results if the threshold is not within the range of y
.