フィルターのクリア

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 Center および File ExchangePolynomials についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by