Row of a Pascal's Triangle using recursion

29 Ansichten (letzte 30 Tage)
Leandro  Cavalheiro
Leandro Cavalheiro am 23 Jul. 2016
Bearbeitet: John D'Errico am 10 Okt. 2020
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 Kommentare
Image Analyst
Image Analyst am 23 Jul. 2016
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 am 10 Okt. 2020
But what should he have done to fix this?

Melden Sie sich an, um zu kommentieren.

Antworten (1)

John D'Errico
John D'Errico am 10 Okt. 2020
Bearbeitet: John D'Errico am 10 Okt. 2020
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.

Kategorien

Mehr zu Polynomials finden Sie in Help Center und File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by