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
2017년 11월 5일
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
2017년 11월 5일
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
카테고리
도움말 센터 및 File Exchange에서 Logical에 대해 자세히 알아보기
제품
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!