MATLAB: Iam trying to run this Horners simple code but i cant because it says ‘Out of memory. The likely cause is an infinite recursion within the program.’

matlab function

function [p]=HornerSimple(a,x)
n=length(a);
i=eye(n);
p=a(n);
for j=n-1:-1:1
p=a(j)*i+HornerSimple(a,x)*x;
end
end

Best Answer

function [p]=HornerSimple(a,x)
Okay, the name of your function is HornerSimple
n=length(a);
i=eye(n);
p=a(n);
for j=n-1:-1:1
None of those lines change a or x
p=a(j)*i+HornerSimple(a,x)*x;
There you call HornerSimple again passing in exactly the same a and x as you originally had. The code path is going to be exactly the same in that call, including calling HornerSimple again with exactly the same a and x as before, so that call would call HornerSimple again with exactly the same, etc.. There is nothing to stop the code from running forever.
Any time you use recursion, in order to have the possibility of the code finishing some time, at least one of the parameters you are passing in to the function must change.
Also notice that each iteration of your for j loop, you are overwriting all of p and p is not involved in the calculation. The result in p is going to end up the same as if you had only executed the last iteration.