필터 지우기
필터 지우기

Writing a Recursive Function

조회 수: 4 (최근 30일)
Mahmoud Abbas
Mahmoud Abbas 2022년 3월 11일
댓글: Mathieu NOE 2022년 3월 11일
I am having trouble writing a recursive function that calculates the value of N(i,p)
for example, to calculate N(0,2), I need the values of N(0,1) and N(1,1). Then each of those will need the values of the lower nodes in the tree as shown below. The value of any N(i,0)=1.

채택된 답변

Mathieu NOE
Mathieu NOE 2022년 3월 11일
hello
see below
Nb : matlab is not a zero based indexing language , so first index is 1 instead of 0
%% initialisation
n = 5;
N = zeros(n,n);
N(1,1:n) = 1; % (all N(i,0) = 1)
%% main loop
for p = 2:n
ind_i = 1:1+n-p; % index of i is function of p (it reduces as index p increases)
N(p,ind_i) = N(p-1,ind_i) + N(p-1,ind_i+1);
end
% display lines in reversed order
N = N(n:-1:1,:)
  댓글 수: 2
Mahmoud Abbas
Mahmoud Abbas 2022년 3월 11일
Wow, Thank You!
Mathieu NOE
Mathieu NOE 2022년 3월 11일
My pleasure !

댓글을 달려면 로그인하십시오.

추가 답변 (1개)

Mathieu NOE
Mathieu NOE 2022년 3월 11일
the results appears like this for n = 5
N =
16 0 0 0 0
8 8 0 0 0
4 4 4 0 0
2 2 2 2 0
1 1 1 1 1
the bottom line is the starting values (Ni,o = 1)

카테고리

Help CenterFile Exchange에서 Matrix Indexing에 대해 자세히 알아보기

제품


릴리스

R2021b

Community Treasure Hunt

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

Start Hunting!

Translated by