필터 지우기
필터 지우기

Row of a Pascal's Triangle using recursion

조회 수: 4 (최근 30일)
Leandro  Cavalheiro
Leandro Cavalheiro 2016년 7월 23일
편집: John D'Errico 2020년 10월 10일
Given a positive integer 'm', I'm writing a code to display the m'th row of Pascal's Triangle. By definition, R m (the m'th row) has m elements, being the first and the last elements equal to 1. The remaining elements are computed by the recursive relationship: R m(i) =R m-1(i-1) + R m-1(i) for i = 2,...,m-1. What I've done so far is :
function [row] = PascalRow(m)
PascalRow(1) = 1;
if m == 1
row = 1;
elseif m == 2;
row = [1 1];
else
row = [1,1];
for i=2:m-1
row(i) = row(i-1) + row(i);
row(m)=1;
end
end
end
but I'm getting 1221, 12221, 122221 for m>3. What am I doing wrong? I haven't caught the hang of this recursion thing yet =(.
  댓글 수: 2
Image Analyst
Image Analyst 2016년 7월 23일
There's no recursion there. With recursion, PascalRow() would call itself inside itself. And since it's a function, you can't assign 1 to it's output
PascalRow(1) = 1; % Not legal
Gijs de Wolf
Gijs de Wolf 2020년 10월 10일
But what should he have done to fix this?

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

답변 (1개)

John D'Errico
John D'Errico 2020년 10월 10일
편집: John D'Errico 2020년 10월 10일
Simplest is to use conv. In terms of your code, I have no idea what you think the line
PascalRow(1) = 1;
does, but it does not belong in a function called PascalRow.
Anyway, this will suffice, as only a single line change to the rest of your code.
function [row] = PascalRow(m)
if m == 1
row = 1;
elseif m == 2;
row = [1 1];
else
row = [1,1];
for i=2:m-1
row = conv([1 1],row);
end
end
end
As a test,
PascalRow(12)
ans =
1 11 55 165 330 462 462 330 165 55 11 1
Could you have done it without use of conv? Of course. For example, this would also have worked, replacing the line I wrote using conv.
row = [row,0] + [0,row];
One final point is, I would probably describe that first "row" of the triangle as the zeroth row. Why? because we can think of the nth row of Pascal's triangle as the coefficients of the polynomial (x+1)^n. As such, the polynomial (x+1)^0 is 1.

카테고리

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

Community Treasure Hunt

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

Start Hunting!

Translated by