Kristian
Kristian

Reputation: 1239

MatLab - Horner's algorithm

I am having some trouble translating a pseudocode for Horner's algorithm into a proper code in MatLab. I think my confusion stems from the fact that the code assumes that the first vector entry can be referred to by 0, whereas in MatLab, this has to be 1. I have tried to modify my code accordingly, but I don't get it to work properly. The pseducode is as follows:

input n, (a_i, : 0 ≤ i ≤ n), z_0
   for k = 0 to n-1 do
      for j = n-1 to k step -1 do
          a_j = a_j + z_0*a_(j+1)
      end do
end do
output (a_i: 0 ≤ i ≤ n)

Here is my attempt at writing this in MatLab, where a is an input vector representing coefficients in a polynomial:

function x = horner(a,z_0)
n = length(a);
for k = 1:n-1
    for j = n-1:-1:k
        a(j) = a(j) + (z_0)*a(j+1);
    end
end
x = a;

I tried this on the vector a = [1 -4 7 -5 -2] which represents coefficients in a polynomial. I also set z_0 = 3. According to my book, I should have received the output vecor a = [1 8 25 37 19], but my code gives the output vector a = [-245 -313 -146 -29 -2].

If anyone can help me clear up this code, I would be very grateful!

Upvotes: 1

Views: 25449

Answers (1)

mathematician1975
mathematician1975

Reputation: 21351

Try this - here a is the vector of polynomial coefficients listed with a(1) as the coefficient of the highest degree term in your polynomial. If your vector is the opposite way round, simply set

b = fliplr(a)

and call the function using vector b. This function will evaluate the polynomial using Horners algorithm. Note that this assumes z_0 is the value that you want the polynomial evaluated at, hence a single value is returned (not a vector)

function x = horner(a,z_0)
n = length(a);
result = a(1);
for j = 2:n
    result = result*z_0 + a(j);
end
x = result;

If you want to pass in a vector of values z to evaluate so you can evaluate multiple points (the elements of z) at the same time, you can pass them in via a vector:

function x = horner(a,z)
n = length(a);
m = length(z);
result = a(1)*ones(1,m);
for j = 2:n
    result = result.*z + a(j);
end
x = result;

now the returned x will be your vector of results

Upvotes: 5

Related Questions