Function Output Not Displaying Why??
Show older comments
function PT=myPascal(n)
PT=zeros(n,n);
for i=1:n
for j=1:i
if n>0
PT(i,j)=factorial(i-1)/(factorial(j-1)*factorial(i-j));
else fprintf ('Error: The input argument is not a positive integer >0')
end
end
end
>> myPascal(5)
ans =
1 0 0 0 0
1 1 0 0 0
1 2 1 0 0
1 3 3 1 0
1 4 6 4 1
>> myPascal(-1)
ans =
[]
Answers (1)
Walter Roberson
on 5 Nov 2017
You have
for i=1:n
for j=1:i
if n>0
The "for i" loop will not have its body executed unless 1:n is non-empty, which requires that n be at least 1. Therefor the test "if n>0" will never be reached unless n is at least 1, so "if n>0" can never be true in that code.
2 Comments
Kim Hao Teong
on 5 Nov 2017
Walter Roberson
on 5 Nov 2017
Correction: n>0 can never be false for that code.
Your code has PT=zeros(n,n) which sets PT to zero.
You should correct your code to
if n < 1
fprintf ('Error: The input argument is not a positive integer')
else
for i=1:n
for j=1:i
PT(i,j)=factorial(i-1)/(factorial(j-1)*factorial(i-j));
end
end
end
Categories
Find more on Logical in Help Center and File Exchange
Products
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!