with this code, im trying to display the results for (y0-y100). But im always getting the error. need help on this.thanks

조회 수: 1 (최근 30일)
for k=1:100
y(k)=y(k-1)*k;
y(0)=1;
end
??? Attempted to access y(0); index must be a positive integer or logical.

답변 (1개)

David Young
David Young 2011년 12월 4일
In MATLAB, indices start from 1. The first time through the loop, the code tries to do this:
y(1) = y(0)*1;
but there is no element y(0).
What you probably need to do is to put the line
y(1) = 1;
before the loop, and start the loop at k=2 by writing "for k=2:100".
  댓글 수: 1
Walter Roberson
Walter Roberson 2011년 12월 4일
You need to go to 101 and you need
y(k) = y(k-1)*(k-1);
The code (explicitly or implicitly) calculates 0! to 100! which is 101 values. If you do not use *(k-1) and do not go to 101, you have the effect of calculating 1! to 100! which is 100 values.

댓글을 달려면 로그인하십시오.

카테고리

Help CenterFile Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기

태그

Community Treasure Hunt

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

Start Hunting!

Translated by