While polynomic psychological analysis seems well beyond my talents, Horner's rule is pretty easy. :) And since you made a credible effort, I'll look at your code. The solution is easier than you think. You were pretty close, though with a couple of significant mistakes.
It looks like you want to evaluate a polynomial with coeffiicents provided in a, at a vector of points in x. So you preallocated y. That is good. And you looped over the coefficients in a. But first, what does Horner's rule mean?
Given a polynomial represented by coefficients in a, such that
a(n+1)*x^n + a(n)*x^n-1 + a(n-1)*x^n-2 + ... + a(1)
then we can write the polynomial as
a(1) + x*(a(2) + x*(a(3) + x*(a(4) + x*(..... ))))))
Horner's method starts in the very deepest part of the parens in that expression. That is, it starts with
y = a(n+1)
Then you multiply by x, and add the preceding coefficient. Repeat until you are done.
(I will point out that this is the opposite sequence the coefficients are stored for tools like polyfit and polyval., but that is not truly relevant here.)
I've carefully called the function myhorner, since there is also a function called horner in the symbolc toolbox. You can name it as you wish.
function y = myhorner(a,x)
n = length(a)-1;
y = repmat(a(n+1),size(x));
for i = n:-1:1
y = y.*x + a(i);
I've added comments in there to explain what I did, however the code itself is still very much yours in its flow and methodology.
Finally, some people might recommend not using i as a loop index. I sort of agee with them, as it then makes creating complex numbers more difficult at some point for you. At the same time, I come from an old school of fortran coders where i was always the loop index in all loops, so I am willing to forgive this use. :)
A quick test of the code is in order. First, does it do what we expected in terms of symbolic manipulations?
a = sym('a',[1,5])
[ a1, a2, a3, a4, a5]
y = myhorner(a,x)
a1 + x*(a2 + x*(a3 + x*(a4 + a5*x)))
a5*x^4 + a4*x^3 + a3*x^2 + a2*x + a1
Yes. That is indeed perfect.
A numerical test seems important too.
myhorner([1 2 3],[-1 0 1 5])
2 1 6 86
You can check those values. Or, we can flip the coefficients around, and use polyval as a check.
polyval([3 2 1],[-1 0 1 5])
2 1 6 86
And, finally, we can plot the function with those coefficients.
fplot(@(x) myhorner([1 2 3],x),[-5,5])
That looks quite reasonably quadratic to me.