mardi 16 février 2021

MATLAB Recursive Pascals Triangle

I am learning about recursive functions. I want to be able to output a row vector 'n' of pascals triangle. k is the element of that row. For example, n = 3, row = 1 2 1.

So far I have tried this, yet unsuccessful. The error I get is that I need to define PT once n > 2. I've looked at other questions on stack overflow however none of them show recursive functions in MATLAB. I tried using a for-loop when n > 2 but that didn't seem to work either.

function row = PT(n,k)

    if n==1
        k = 1;
        PT(n,k) = 1;
        row = [1];
    elseif n==2
        if k == 1
            PT(n,k) = 1;
        else k == 2
            PT(n,k) = 1;
        end
        row = [1 1];
        
    else n > 2;
     
        PT(1,1) = [1];
        PT(2,1) = [1];
        PT(2,2) = [1];
        row = [PT(2,1), PT(2,2)];
        row = [PT(n-1,k-1)+ PT(n-1,k)];
           
end
end

Aucun commentaire:

Enregistrer un commentaire