MATLAB: Finding Steepest Linear Portion of Data

fitlmgraphlinearMATLABportionregionregressionslopesteepeststrainstress

I've been trying to use fitlm as a way of finding the steepest linear portion of a graph but cannot get it to work correctly. Perhaps there is a better way I could be finding this out?
Essentially I have data (stress and strain) which looks like the following:
I'm trying to use Matlab to automatically find the steepest linear portion of the graph. This is what I have been trying so far using the fitlm function.
R=0;
for x = 100:size(strain)
fitlm(strain(10:x),stress(10:x));
if ans.Rsquared.Ordinary > R
R=ans.Rsquared.Ordinary;
index=x;
end
end
I can get the code to go along the data and find out where the r-squared value seems to fit best and identify a linear region of the data, but how can I get Matlab to identify the steepest linear region?
This is the output of plotting from the start of the data to the index point:

Best Answer

You have a non-linear model, so fitting linear segments is likely not going to be easy. The best way to fit your data is to use a model of the process that created your data (if you have an analytical version of it) and then a non-linear regression, such as fitnlm or nlinfit. Then take the analytic derivative of the fitted function.
If you’re looking for linear segments in your data and don’t want to fit it, I would start by using the gradient function to calculate the numerical derivative of your data (since they appear reasonably noise-free). This should produce a series of ‘steps’ that are flat in the linear sections. Choose the one that meets your criteria in terms of length and ‘flatness’, and use it. One of the histogram functions could be helpful here, since you can define the ranges of the bins. This will eliminate a lot of tedious threshold programming. (I don’t have your data, so I can’t write code to analyse it.)
Related Question