function a = mypolyfit(x, y, n)
%MYPOLYFIT polynomial least squares fit of (x ,y) data.
%          Return the coefficients of the polynomial
%          p(x) = a(1) + a(2)*x + a(3)*x^2 + ... + a(n+1)*x^n
    m = length(x);
    b = zeros(n+1, 1);
    A = zeros(n+1, n+1);
    w = ones(m, 1);
    for i = 1:(n+1)
        b(i) = y*((x.^(i-1)))';
    end
    A(1, 1) = m;
    for i = 2:(n+1)
        w = w.*x';
        s = sum(w);
        for j = 1:i
            A(j, i+1-j) = s;
        end
    end
    for i = 2:n+1
        w = w.*x';
        s = sum(w);
        for j = i:n+1
            A(j, n+i+1-j) = s;
        end
    end
    a = A\b;
end

