从 polyfit 图中提取给定 y 阈值的 x 值 (Matlab)

Extracting x value given y threshold from polyfit plot (Matlab)

如实线和虚线所示,我想创建一个函数,在该函数中,我根据该阈值设置 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

这里不需要 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 );

请注意,如果没有 y 值超过阈值,xDesired 将为空。


或者,您已经有了多项式拟合,因此您可以使用 fzero 获得给定 y 的多项式的 x 值(在本例中为您的阈值) .

% 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范围内,此方法可能会产生意想不到的结果。