Identify a segment of the curve (x, y) that appears to be linear. function [range poly] = identify_linear_piece(x, y, window_length) This function attempts to identify a contiguous segment of the curve defined by the vectors x and y that appears to be linear. A line is fit through the data over all windows of length window_length and the best fit is retained. The output specifies the range of indices such that x(range) is the portion over which (x, y) is the most linear and the output poly specifies a first order polynomial that best fits (x, y) over that range, following the usual matlab convention for polynomials (highest degree coefficients first). See also: checkdiff checkgradient checkhessian
0001 function [range, poly] = identify_linear_piece(x, y, window_length) 0002 % Identify a segment of the curve (x, y) that appears to be linear. 0003 % 0004 % function [range poly] = identify_linear_piece(x, y, window_length) 0005 % 0006 % This function attempts to identify a contiguous segment of the curve 0007 % defined by the vectors x and y that appears to be linear. A line is fit 0008 % through the data over all windows of length window_length and the best 0009 % fit is retained. The output specifies the range of indices such that 0010 % x(range) is the portion over which (x, y) is the most linear and the 0011 % output poly specifies a first order polynomial that best fits (x, y) over 0012 % that range, following the usual matlab convention for polynomials 0013 % (highest degree coefficients first). 0014 % 0015 % See also: checkdiff checkgradient checkhessian 0016 0017 % This file is part of Manopt: www.manopt.org. 0018 % Original author: Nicolas Boumal, July 8, 2013. 0019 % Contributors: 0020 % Change log: 0021 0022 residues = zeros(length(x)-window_length, 1); 0023 polys = zeros(2, length(residues)); 0024 for i = 1 : length(residues) 0025 range = i:(i+window_length); 0026 [poly, meta] = polyfit(x(range), y(range), 1); 0027 residues(i) = meta.normr; 0028 polys(:, i) = poly'; 0029 end 0030 [unused, best] = min(residues); %#ok<ASGLU> 0031 range = best:(best+window_length); 0032 poly = polys(:, best)'; 0033 0034 end