how to call and use function Recursivity

I have an exercise with newton way calculate y(x+1)=y(x)-f(x)/f'(x) in this function I need y(x) and for this I use function Recursivity for y(1) & y(2) it's working because y(1) has formula y(1)=R*T/p ,for save y(x) I use zeros()to use when calculate y(x+1) but for x>2 I get the same answer,what am I missing??what can I use instead of zeros() for save and access to newt(x-1)??
function y= newt(x)
%define beta,gamma,delta,....there
y(1)=R*T/p;
answ=zeros(1,20);
z=0;
if x==1
f=(R*T*y(1)^3)+(beta*y(1)^2)+(gamma*y(1))+delta-(p*y(1)^4);
f1=(3*y(1)^2*R*T)+(2*y(1)*beta)+gamma+(4*p*y(1)^3);
answ(1) = y(1);
fprintf('n=1 v=%f\n',y(1));
else
y=newt(x-1);
f=(R*T*y^3)+(beta*y^2)+(gamma*y)+delta-(p*y^4);
f1=(3*y^2*R*T)+(2*y*delta)+gamma+(4*p*y^3);
z=y-f/f1
answ(1,2:x)=z;
end
answ(1) = y(1);
answ(1,2:x)=z;

Answers (1)

You have not understood how recursive functions work:
function y = newt(x)
%a recursive function calls itself except at the boundary
if x > 1 %normal case
f = ...
divf = ...
y = newt(x - 1) - f(x-1) / divf(x-1);
else %boundary case
y = R * T / p;
end
end

2 Comments

@Guillaume tank you for response,for calculate f and divf must use y(x-1),according to your answer if y = newt(x - 1) - f(x-1) / divf(x-1); after f and divf function the answer is wrong, I set y(x-1) in f and divf
f = (R*T*y(x-1)^3)+(beta*y(x-1)^2)+(gamma*y(x-1))+delta-(p*y(x-1)^4);
divf = (3*y(x-1)^2*R*T)+(2*y(x-1)*beta)+gamma+(4*p*y(x-1)^3);
In your question, the equation for y is y(x+1)=y(x)-f(x)/f'(x). According to that equation f does not depend on y.
What is the equation of f?

This question is closed.

Asked:

on 4 Aug 2016

Closed:

on 20 Aug 2021

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!