% Matlab Program To Fit Straight Line/first Degree Curve (Y Ax+b)
% Matlab Program To Fit Straight Line/first Degree Curve (Y Ax+b)
% Matlab Program To Fit Straight Line/first Degree Curve (Y Ax+b)
clc;
clear;
n=input('\nEnter the value of data entries n= ');
for i=1:1:n
x(i)=input('Enter the values of x= ');
y(i)=input('Enter the values of y= ');
end
sx=0;
sy=0;
sxx=0;
sxy=0;
for i=1:1:n
sx=sx+x(i);
sy=sy+y(i);
sxx=sxx+x(i)*x(i);
sxy=sxy+x(i)*y(i);
end
delta=sxx*n-sx*sx;
delta1=sxy*n-sy*sx;
delta2=sxx*sy-sx*sxy;
a=delta1/delta;
b=delta2/delta;
fprintf('\nThe values of constants a=%f and b=%3f',a,b);
fprintf('\nThe equation of straight line is y=%2.5f x + %2.5f',a,b);
% Plotting best fit curve y=ax+b using points (x, ya) and observed curve using (x, y)
for i=1:1:n
ya(i)=a*x(i)+b; %To find the calculated ya using eq. ya=ax+b as per solution
end
hold on
plot(x,y,'b*-');
plot(x,ya,'r+-');
xlabel('X');
ylabel('Y');
title('Graph of first degree curve using least square criteria');
OUTPUT
OUTPUT
OUTPUT
OUTPUT