% Evaluate f\left(x\right)=6x^3 +4x^2 +7x+19
%

% Coefficients
clear
format short
a=[19, 7, 4, 6]
n=length(a)-1;
x=1.5;

%

% MATLAB Built-in function
P=fliplr(a)
f_matlab = polyval(P,x)

%

% Naive Evaluation
p=0;
for k=0:n
    p=p+a(k+1)*x^k;
end

f_naive=p

%

% Iteration
p=0;
xn=1;
for k=0:n
    p=p+xn*a(k+1);
    xn=xn*x;
end

f_iter=p

%

% Horner's Method using function
f_horner=hornerfn(P,x)

%

function y = hornerfn(c,x)
% HORNER   Evaluate a polynomial using Horner's rule. 
% Input:
%   c     Coefficients of polynomial, in descending order (vector)
%   x     Evaluation point (scalar)
% Output:
%   y     Value of the polynomial at x (scalar)

n = length(c);
y = c(1);
for k = 2:n
  y = x*y + c(k);
end

end