如实线和虚线所示,我想创建一个函数,在该函数中我从该阈值设置y(强度)的阈值,从而为我提供了对应的x值(虚线)。非常简单,但我的while语句已关闭。任何帮助将非常感激!
%% Curve fit plotting %%
x1 = timeStamps(1:60); % taking timestamps from 1 - 120 given smoothed y1 values
y1 = smooth(tic_lin(1:60),'sgolay',1);
% Find coefficients for polynomial (order = 4 and 6, respectively)
fitResults1 = polyfit(x1',y1, 7);
% evaluate the fitted y-values
yplot1 = polyval(fitResults1,x1');
% interpolates to find yi, the values of the underlying function Y at the points in the vector or array xi. x must be a vector.
Time_points = interp1(yplot1, x1', yplot1);
figure( 'Name', 'Curvefit1_poly' );
h = plot(x1', y1);%smoothed-points
hold on;
plot(x1', yplot1);%polyfit points
hold on;
plot(Time_points, yplot1, '*r');%interpolated points of x given y
%given y-threshold, output x(corresponding time_point).
broken = false;
while broken == false
if yplot1 >= 2024671226502.99
index = find(yplot1);
xDesired = x1(index);
broken = true;
else
disp("next iteration through");
end
end
答案 0 :(得分:4)
这里不需要while
循环...您可以使用阈值条件的逻辑索引和find
来获得第一个索引:
% 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 );
请注意,如果没有xDesired
的值没有超过阈值,则y
将为空。
或者,您已经具有多项式拟合,因此您可以使用fzero
来获得给定x
的多项式上的y
值(在这种情况下为阈值)。 / p>
% 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) )
请注意,如果阈值不在y
范围内,则此方法可能会产生意外结果。