Bell Triangle function problem:

1 view (last 30 days)
Amit Tal
Amit Tal on 31 Aug 2015
Edited: Stephen23 on 1 Sep 2015
Hello, I am having trouble writing a program that displays the Bell Triangle to the 'n'th row, but I run into a problem when I want the program to return an empty array for decimal inputs. I tried changing my code (see below) but now I get an empty array no matter the input (it worked before).
Prompt: 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.
My code:
function B = bell(n)
if n<=0 || isinteger(n)==false
B=[];
else B(1,1) = 1;
for i=2:n
B(i,1) = B(1,end);
for j = 1:i-1
B(i-j,j+1) = B(i-j+1,j)+B(i-j,j);
end
end
end
Any help would be greatly appreciated. Cheers!

Answers (1)

Walter Roberson
Walter Roberson on 31 Aug 2015
Edited: Stephen23 on 1 Sep 2015
tf = isinteger(A) returns true if the array A is an integer type and false otherwise.
If you want to check whether the value is integer, check to see if n == floor(n)
  2 Comments
Amit Tal
Amit Tal on 31 Aug 2015
If I understand correctly, floor would round the 1.5 input down to 1. However, I wish the function to return an empty array if the input is not integral. Could I still do that with floor?
Walter Roberson
Walter Roberson on 31 Aug 2015
if n <= 0 || n ~= floor(n)
B = [];
By the way: what happens if someone passes in a vector?

Sign in to comment.

Categories

Find more on Matrices and Arrays in Help Center and File Exchange

Community Treasure Hunt

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

Start Hunting!