Assignment 3
Assignment 3
coeff=[-4 0 3 -2 1];
power=50;
result=1;
for i=1:power
result=conv(result,coeff);
end
coeffocient=result(end-power);
disp(coeffocient);
Problem 2a
clc; clear all; close all;
N=[2 3 4 5 6];
figure;
for i=1:length(N)
n=N(i);
x=linspace(-.5,.5,n);
y=sin(pi*x);
F = 0;
for j=1:n
p=1;
for k=1:n
if(j~=k)
temp = [1,-x(k)]/(x(j)-x(k));
p=conv(p,temp);
end
end
F=F+p*y(j);
end
x_1=linspace(-.5,.5,1000);
y_test=polyval(F,x_1);
y_real=sin(pi*x_1);
E=y_real - y_test;
y1 = polyval(F, x);
plot(x,y1,'DisplayName', ['N = '
num2str(n)],'LineWidth',2);
hold on;
title('Lagrange Polynomial Interpolation for sin(\pi
x)');
xlabel('x');
ylabel('y');
legend('show');
grid on;
end
plot(x_1,y_real,'LineWidth',2)
Problem 2b
clc; clear all; close all;
N=[2 3 4 5 6];
figure;
for i=1:length(N)
n=N(i);
x=linspace(-.5,.5,n);
y=sin(pi*x);
F = 0;
for j=1:n
p=1;
for k=1:n
if(j~=k)
temp = [1,-x(k)]/(x(j)-x(k));
p=conv(p,temp);
end
end
F=F+p*y(j);
end
x_1=linspace(-.5,.5,1000);
y_test=polyval(F,x_1);
y_real=sin(pi*x_1);
E=y_real - y_test;y1 = polyval(F, x);
subplot(2,3,i);
plot(x_1,E,'DisplayName', ['N = '
num2str(n)],'LineWidth',2);
hold on;
title('Lagrange Polynomial Interpolation for sin(\pi
x)');
xlabel('x');
ylabel('y');
legend('show');
grid on;
end
Explanation
The error for N=2,3 is higher compared to the other four values. This is because,
for N=2,3, the regression is conducted between only two points, leading to a less
accurate approximation and higher errors. As we increase the number of points,
the interpolation becomes more refined, resulting in a more accurate
approximation with reduced errors.
Problem 3
clc; clear all; close all;
x=[1 3 4 7 8 10];
y=[2.1 4.6 5.4 6.1 6.4 6.6];
% Linearisation
y1=1./y;
x1=1./x;
% Matrix Declaration
coeff=[length(x1),sum(x1);sum(x1),sum(x1.^2)];
Value=[sum(y1);sum(x1.*y1)];
solution=inv(coeff)*Value;
% Plotting Points
plot(x,y,'ok','LineWidth',2);
hold on;
a0=solution(1);
a1=solution(2);
fx=a0+a1*x1;
plot(x,1./fx,'LineWidth',2);
xlabel('x');
ylabel('y');
title('best fitted','FontSize',15);
legend('Points','Best fitted line');
m=1/a0
b=a1*m
mdl_linear=fitlm(x1, y1);
% x values
y_predicted_poly=polyval(coefficients, x_values);
plot(x_values, y_predicted_poly, 'r-', 'LineWidth', 2,
'DisplayName', 'Polynomial Fit');
ylim([0,15]);
hold off;
mdl_linear=fitlm(x, y);
plot(mdl_linear,'LineWidth',2)