clc clear all x=[-2 -1 0 1 2] y=[15 1 1 3 19] N=length(x) M=[N sum(x); sum(x) sum(x.^2)]
L=inv(M)*B
f=L(1)+ L(2)x plot(x,y,'r') hold on plot(x,f,'b-')
M1=[N sum(x) sum(x.^2); sum(x) sum(x.^2) sum(x.^3); sum(x.^2) sum(x.^3) sum(x.^4)] B1=[sum(y);sum(x.y);sum(x.^2.y)] L2=inv(M1)B1 f1=L2(1)+L2(2)x+L2(3)*x.^2 plot(x,f1,'k-')
x1=[-2 -1 0 1 2]; y1=[15 1 1 3 19]; syms x y a b n=length(x1); g=@(a,b,x,y)((y-a-bx))^2; g1=@(a,b,x)(a+bx); h = diff(g,a); h1 = diff(g,b); k = subs(h, {x,y}, {x1,y1}); k1 = subs(h1, {x,y}, {x1,y1}); m = sum(k); m1 = sum(k1); equations = [m==0, m1==0] [A c] = equationsToMatrix(equations); X=inv(A)c; a1=X(1) b1=X(2) f=g1(a1,b1,x1); plot(x1,y1,'r-',x1,f,'b-^');
n= input("Enter the number of data points : "); x= input("Data Points : "); f= input("Value of f(x) : "); A= zeros(2,2); B= zeros(2,1); A(1,1)=n; for i=1:n A(1,2)= A(1,2)+x(i); A(2,2)= A(2,2) + (x(i)x(i)); B(1)= B(1)+f(i); B(2)= B(2) +(f(i)x(i)); end A(2,1)= A(1,2); Solution= linsolve(A,B); fprintf("Value of a : %0.5f\nValue of b : %0.5f",Solution(1),Solution(2));