Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 2

Homework 2

Numerical Analysis

Student name: Nihad Hasanović

Student ID: 150302101

Task 1:

clc
clear all
close all
format long
x=0:0.2:1;
y=sin(x);
[a,Er]=LinFit(x,y)
plot(x,y,'o',x,polyval(a,x));
function [a,Er]=LinFit(x,y)
A=[x(:).^(1:-1:0)];
b=y(:);
a=A\b;
Er=sum(abs(polyval(a,x)-y));
end

Task 2:

close all
clear
clc
x = 1:10;
y = 2*x.^2 + 3*x + 5;
[a, Er] = QuadFit(x, y)
function [a, Er] = QuadFit(x, y)
x = x(:); y = y(:);
A = [x.^2 x ones(size(x))];
a = inv(A' * A) * A' * y;
Er = norm(A*a - y);
figure, plot(x, y, 'o'), hold on
x_vals = linspace(min(x), max(x));
plot(x_vals, a(1)*x_vals.^2 + a(2)*x_vals + a(3)), hold off
xlabel('x'), ylabel('y'), title('Least Squares Curve Fitting')
legend('Data Points', 'Quadratic Fit', 'Location', 'northwest')
end
Task 3:

clc
clear all
close all
format long
x=0:0.2:1;
y=sin(x);
[a,Er]=CubicFit(x,y)
plot(x,y,'o',x,polyval(a,x));
function [a,Er]=CubicFit(x,y)
A=[x(:).^(3:-1:0)];
b=y(:);
a=transpose(A\b);
Er=sum(abs(polyval(a,x)-y));
end

You might also like