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

时间:2018-08-14 15:06:35

标签: matlab curve-fitting data-extraction

enter image description here enter image description here

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

1 个答案:

答案 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范围内,则此方法可能会产生意外结果。