You are on page 1of 3

MACHINE EXERCISE 3: GENERAL LEAST SQUARES

As a student of the University of the Philippines, I pledge to act ethically and uphold the value of
honor and excellence.

I understand that suspected misconduct on this Assignment will be reported to the appropriate
office and if established, will result in disciplinary action in accordance with University rules,
policies and procedures. I may work with others only to the extent allowed by the Instructor.

Name: BUDUAN, BERNARD KARLO B.


Student Number: 200528644

Write a MATLAB code that generates the Nth degree polynomial least squares
matrix.

INPUT:
1. (x,y) dataset
2. Degree of polynomial
OUTPUT:
Least squares matrix

MATLAB CODE

%Input the x values


%x_i = [1 2 3 4 5]
x_i = [0.050 0.110 0.150 0.310 0.460 0.520 0.700 0.740 0.820 0.980 1.170]

%Input the y values


%y_i = [2.2 3.6 3.7 4.6 6.1]
y_i = [0.956 0.890 0.832 0.717 0.571 0.539 0.378 0.370 0.306 0.242 0.104]

%Input the degree of the polynomial, N


%N = 1
N = 3

%The graph of y vs x
plot(x_i,y_i, 'or', 'MarkerSize',5);
%Generate the Vander Matrix for x_i
x_vander = fliplr(vander(x_i));

%Limit the Vander Matrix to the Power N


x_vander_N = x_vander(:, 1:N+1);

%Limit the Vander Matrix to the Power 2N


x_vander_2N = x_vander(:, 1:2*N+1);

%Get the sum of the Vander Matrix limited to the Power 2N


x_van_sum = sum(x_vander_2N);

%Preallocate the Least Squares Matrix


lsm = ones(N+1);

%Generate the Least Squares Matrix


counti = 0;
for i = 1:N+1
countj = 0;
for j = 1:N+1
lsm(i,j)=x_van_sum(:,counti+j);
countj = countj + 1;
end
counti = counti + 1;
end

%Display the Least Squares Matrix


lsm

%Generate the Right Hand Side Vector


rhs = transpose(y_i*x_vander_N)

%Generate the Coefficients


coefficients = lsm \ rhs

SAMPLE OUTPUT

You might also like