What you are trying to do is called linear time series segmentation.
There are many methods to solve this problem, which are distinguished by their complexity and accuracy.
Here is the simplest one called sliding window segmentation:
function [breaks vals] = segment( data, max_error ) breaks = []; vals = []; left = 1; for right = 2:length(data) err = linear_regresion(data(left:right)); if max(abs(err)) > max_error breaks(end+1) = right-1; vals(end+1) = data(right-1); left = right; end end end function err = linear_regresion( data ) n = length(data); x = (1:n)' - (n+1)/2; y = data - mean(data); k = sum(x.*y) ./ sum(x.^2); err = y - k*x; end
linear_regresion is an implementation of a simple linear regression algorithm .
In my example, I used the maximum absolute error as a stopping criterion, but you can replace it with any other fitting function, for example. means square error .
Here is an example of segmenting your data using max_error = 0.04 :

You can find about this and other segmentation methods in this review article .
source share