## Linear best fit through specified y-axis intercept

Asked by Matt Edwards

### Matt Edwards (view profile)

on 13 Nov 2019
Latest activity Answered by Star Strider

### Star Strider (view profile)

on 13 Nov 2019
Essentially I have a few data points grouped closely together and they require a linear best fit line. However, the best fit line needs extrapolating to a specific y-axis intercept. I'm not too sure how to approach this. Using a polyfit I get this result:
The y intercept has to be 1.68. So I presume the gradient has to be modified as well as the intercept to get the correct linear best fit line. How would I go about this?

### David Hill (view profile)

Answer by David Hill

### David Hill (view profile)

on 13 Nov 2019

f=fit(x,y,'poly1');
disp(f);%will display the linear model including the y-intercept and slope of the fitted line

### Star Strider (view profile)

Answer by Star Strider

### Star Strider (view profile)

on 13 Nov 2019

Try this:
x = linspace(0.7, 1.7, 5); % Create Data (Use Your Own ‘x’ & ‘y’)
y = randn(1,5); % Create Data (Use Your Own ‘x’ & ‘y’)
xp = [0 2]; % X-Vector For Plot
B = x(:) \ (y(:)-1.68);
yp = xp(:)*B+1.68;
Bnew = [xp(:) ones(size(xp(:)))] \ (yp(:)); % Calculate New Regression Parameters
figure
plot(x, y, '*')
hold on
plot(xp, yp, '-r')
plot(0, 1.68, '+g')
hold off
grid
xlim([0 2])
text(1, 1.5, sprintf('y = %.2f%+.3f\\cdotx', Bnew(2),Bnew(1)))
The ‘Bnew’ calculation is not absolutely necessary, since it is simply [B; 1.68]. I added it essentially to demonstrate that the new regression on ‘xp’ and ‘yp’ does actually result in the desired parameters.