title: MatLab - Horner's algorithm
body: <p>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:</p>
  
  <pre><code>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)
  </code></pre>
  
  <p>Here is my attempt at writing this in MatLab, where <code>a</code> is an input vector representing coefficients in a polynomial:</p>
  
  <pre><code>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;
  </code></pre>
  
  <p>I tried this on the vector <code>a = [1 -4 7 -5 -2]</code> which represents coefficients in a polynomial.  I also set <code>z_0 = 3</code>.  According to my book, I should have received the output vecor <code>a = [1 8 25 37 19]</code>, but my code gives the output vector <code>a = [-245  -313  -146   -29    -2]</code>.</p>
  
  <p>If anyone can help me clear up this code, I would be very grateful!</p>