Ezzataii
Ezzataii

Reputation: 1

Creating a Recursive Function that Generates Pascal's Triangle (Matlab)

I've been trying to figure out how to recursively generate Pascal's triangle in a matrix using Matlab. Here is an example of how it should look like:

 >>PascalT(0)  
 ans =  
  1

 >>PascalT(1)  
 ans =  
  0 1 0  
  1 0 1

 >>PascalT(2)  
 ans =  
  0 0 1 0 0   
  0 1 0 1 0  
  1 0 2 0 1

 >>PascalT(3)  
 ans =  
  0 0 0 1 0 0 0  
  0 0 1 0 1 0 0   
  0 1 0 2 0 1 0  
  1 0 3 0 3 0 1

My code so far is pretty empty because I can't figure out how to do it:

function AA = PascalT(n)  
    if n == 0   
        AA = 0;  
    else  
        rec = PascalT(n-1);  
        AA = zeroes(n+1,2*n+1);  

    end  
end

Upvotes: 0

Views: 1637

Answers (1)

Wolfie
Wolfie

Reputation: 30046

Why does this need to be recursive? You know how many numbers are in each row of the triangle, and can just loop down it the matrix...

function AA = PascalT( n )
    % Initialise matrix. Use 2n+3 cols so that we have additional 0s for edges
    AA = zeros(n+1, 2*n + 3);
    % First row...
    AA(1, n+2) = 1;
    % Loop over rows         
    for r = 2:n+1
        % Create row r by adding left-shifted and right-shifted row above
        AA(r, 2:end-1) = AA(r-1, 1:end-2) + AA(r-1, 3:end);
    end
    % Remove extra zeros on the edges
    AA = AA(:, 2:end-1);
end

Note: there is an in-built function pascal which returns the Pascal triangle (rotated by 45 degrees compared to yours) which you may find useful.

Upvotes: 3

Related Questions