How to generate recursive formula with two initial values?

8 vues (au cours des 30 derniers jours)
Sohail
Sohail le 31 Déc 2013
Commenté : meenakshi le 15 Jan 2018
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

Réponse acceptée

Roger Stafford
Roger Stafford le 31 Déc 2013
Modifié(e) : Roger Stafford le 31 Déc 2013
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

Plus de réponses (1)

Walter Roberson
Walter Roberson le 31 Déc 2013
The general form of those kinds of recursive functions is
function r = recursive_function(N)
if N > number_of_initial_values
r = SomeOperation( N, recursive_function(N-1), recursive_function(N-2), ...)
else
switch N
case 1: r = first_initial_value;
case 2: r = second_initial_value;
....
end
end
end
where SomeOperation() is the mathematical operation connecting the various values. For example for simple Fibonacci sequences,
r = recursive_function(N-1) + recursive_function(N-2);
  1 commentaire
meenakshi
meenakshi le 15 Jan 2018
clc; clear all; close all; N=5; syms a p %intial values of D a=10; p=0.1; D(1)=1+a*p; D(2)=3+3*a*p+a^2*p^2; % %Recursive formula for D for N=3:4 D(N)=(2*N-1).*D(N-1)+a^2*p^2.*D(N-2) end

Connectez-vous pour commenter.

Catégories

En savoir plus sur Symbolic Math Toolbox dans Help Center et File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by