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!
Try this – here
ais 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 setand call the function using vector
b. This function will evaluate the polynomial using Horners algorithm. Note that this assumesz_0is the value that you want the polynomial evaluated at, hence a single value is returned (not a vector)If you want to pass in a vector of values
zto evaluate so you can evaluate multiple points (the elements ofz) at the same time, you can pass them in via a vector:now the returned
xwill be your vector of results