How to generate recursive formula with two initial values?

조회 수: 8 (최근 30일)
Sohail
Sohail 2013년 12월 31일
댓글: meenakshi 2018년 1월 15일
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에서 Symbolic Math Toolbox에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by