Row of a Pascal's Triangle using recursion

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

请先登录,再进行评论。

回答(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