Borrar filtros
Borrar filtros

How to generate recursive formula with two initial values?

5 visualizaciones (últimos 30 días)
Sohail
Sohail el 31 de Dic. de 2013
Comentada: meenakshi el 15 de En. de 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

Respuesta aceptada

Roger Stafford
Roger Stafford el 31 de Dic. de 2013
Editada: Roger Stafford el 31 de Dic. de 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

Más respuestas (1)

Walter Roberson
Walter Roberson el 31 de Dic. de 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 comentario
meenakshi
meenakshi el 15 de En. de 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

Iniciar sesión para comentar.

Categorías

Más información sobre Entering Commands en Help Center y File Exchange.

Etiquetas

Community Treasure Hunt

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

Start Hunting!

Translated by