Search Program on this blog

Thursday 27 August 2015

Write a function called bell that returns the first n rows of the Bell triangle, where n is an input argument. For a precise definition, see http://en.wikipedia.org/wiki/Bell_triangle. The function must return an n-by-n array where the top left triangle contains the Bell triangle with each row of the Bell triangle positioned diagonally—bottom-left-to-upper-right—and the bottom right triangle contains only zeros. If n is not a positive integer, the function returns an empty array.

function B = bell(n)
%Input n is a positive integer
%Output B is an array of nxn
%Example B=bell(7)
if n<1 || fix(n)~=n  %check if n is a positive integer
    B=[];
    return;
end
B = zeros(n);
B(1,1) = 1;
for row=2:n
  B(row, 1:row) = B(row-1,row-1) + cumsum([0 B(row-1, 1:row-1)]);
end
A=B(:,1);
count=n-1;
for i=2:n
    C=circshift(B(:,i),count);
    A=[A C];
    count=count-1;
end
B=A;

No comments:

Post a Comment