How to generate recursive formula with two initial values?

3 次查看(过去 30 天)
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

采纳的回答

Roger Stafford
Roger Stafford 2013-12-31
编辑:Roger Stafford 2013-12-31
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

更多回答(1 个)

Walter Roberson
Walter Roberson 2013-12-31
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 个评论
meenakshi
meenakshi 2018-1-15
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

请先登录,再进行评论。

类别

Help CenterFile Exchange 中查找有关 Matrices and Arrays 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by