## Setting a limit for a linear fit line

### Benjamin Strasser (view profile)

on 22 Feb 2019
Latest activity Edited by Cris LaPierre

### Cris LaPierre (view profile)

on 9 Apr 2019
I have a set of points resembling the beginning of a stress strain cure, if anyone knows what that is. I have the linear fit line created for the points, but I need to set it to a certain group of the points (from one x axis value to another). How would I go about setting that limit?

### Cris LaPierre (view profile)

on 9 Apr 2019

How are you fitting? Are you using polyfit? fit? fminsearch?
MATLAB will only fit the data points you give it. If you want to limit the fit to specific values, just pass the specific values to your fitting function.
Since I assume you just need the slope to obtain the modulus of elasticity, I'd probably use polyfit. Consider the example given here. If I wanted to limit the fit to x values between [15 30], I'd modify the code as follows:
x = 1:50;
y = -0.3*x + 2*randn(1,50);
ind = x>=15 & x<=30;
p = polyfit(x(ind),y(ind),1);
f = polyval(p,x(ind));
plot(x,y,'o',x(ind),f,'-')
legend('data','linear fit')

### Image Analyst (view profile)

on 9 Apr 2019

I think he already has the fit (fitting coefficients) -- at least that's what he said -- so I think he just wants to evaluate the same fitting parameters over a set of x values that are not the same as the training x values.
Here I do that and use two new x scales - one that's within the training set, and one that is outside the training set (which makes it extrapolate (risky)):
% Create sample data.
x = 1:50;
y = -0.3*x + 2*randn(1,50);
plot(x, y, 'bo');
xlabel('x', 'FontSize', 18);
ylabel('y', 'FontSize', 18);
grid on;
% Now do the fitting.
coefficients = polyfit(x, y, 1);
% Now apply this fit to x in the range -10, 60
x2 = linspace(-10, 60, 100); % 100 points in between -10 and 60
yFit2 = polyval(coefficients, x2);
hold on;
plot(x2, yFit2, 'r-', 'LineWidth', 3) ;
% Now apply this fit to x in the range 15, 30
x3 = linspace(15, 30, 100); % 100 points in between -10 and 60
yFit3 = polyval(coefficients, x3);
plot(x3, yFit3,'c-', 'LineWidth', 4)
legend('Training data', 'Extrapolated fit', 'Interior fit')
title('Both lines use same fitting results', 'FontSize', 18);

Cris LaPierre

### Cris LaPierre (view profile)

on 9 Apr 2019
I disagree. It sounds like he is fitting all the points, but with stress-strain data, you only want to fit the linear portion at the beginning ("I need to set it to a certain group of the points (from one x axis value to another")).
Fitting too many points will flatten out your line and result in an inaccurate estimate of the slope (modulus of elasticity).