MATLAB: How to generate recursive formula with two initial values

recursive formula

Hi Everyone,
I am having difficulty in writing code for recursive formula. Here is the code
clc;
clear all;
close all;
N=5;
syms a p
%intial values of D
D(1)=1+a*p;
D(2)=3+3*a*p+a^2*p^2;
%Recursive formula for D
D(N)=(2*N-1)*D(N-1)+a^2*p^2*D(N-2)
How to find the value of D for N=5?
Thanks

Best Answer

Recursion for a value N which calls on itself twice, once for N-1 and another time for N-2, gives rise to an exponentially increasing number of total calls as N increases. For example, for N equal to 10 there will be approximately 100 recursive calls made altogether on itself. That is not an efficient way to do recursion.
It is far better to construct the calls in such a way that the number only increases linearly with N. For Sohail's particular problem we can do this by returning two successive values of D from the call instead of one.
function [D,D0] = Sohail(N) % D is the value corresponding to N and D0 is for N-1
if N > 1
[D0,D00] = Sohail(N-1);
D = (2*N-1)*D0+a^2*p^2*D00;
elseif N == 1
D = 1+a*p;
D0 = 1;
end
return
However, I would think an ordinary for-loop a far better method than any of the above types of recursion.
D0 = 1;
D = 1+a*p;
for n = 2:N
t = (2*n-1)*D+a^2*p^2*D0;
D0 = D;
D = t;
end
% At exit D will be the value corresponding to N
Related Question