Function Output Not Displaying Why??

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 =
[]

回答 (1 件)

Walter Roberson
Walter Roberson 2017 年 11 月 5 日

0 投票

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 件のコメント

Kim Hao Teong
Kim Hao Teong 2017 年 11 月 5 日
im confused in which part of the code i have defined something = 0?
Walter Roberson
Walter Roberson 2017 年 11 月 5 日
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

サインインしてコメントする。

カテゴリ

製品

質問済み:

2017 年 11 月 5 日

コメント済み:

2017 年 11 月 5 日

Community Treasure Hunt

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

Start Hunting!

Translated by