Info

이 질문은 마감되었습니다. 편집하거나 답변을 올리려면 질문을 다시 여십시오.

# for loop help matlab error

조회 수: 4 (최근 30일)
B 2015년 3월 24일
마감: MATLAB Answer Bot 2021년 8월 20일
I really can't understand the arrays and matrices system in matlab...:( Please help with the following; I'm getting (??? Attempted to access Tc(21); index out of bounds because numel(Tc)=20.
Error in ==> newestt at 9 Tc0=Tc(i);) ================================================================================================== num=20; for i=2:num; Tc0=110; Tc(20)=27; Tc(1)=109; detaTc=(Tc0-Tc(20))/num; Tc(i)=(Tc0- detaTc) i=i+1; Tc0=Tc(i); end
Thanks!~

### 답변 (2개)

Julia 2015년 3월 24일
Hi,
The error states clearly, that you try to access the 21st entry of Tc, but Tc has only 20 entries:
i=i+1;
Tc0=Tc(i);
In the last iteration for i=num (in your example i=20), this leads to the error.
##### 댓글 수: 3이전 댓글 1개 표시이전 댓글 1개 숨기기
Stephen23 2015년 3월 24일
편집: Stephen23 2015년 3월 24일
@B: What do you expect MATLAB to do? The array has twenty elements, and you are trying to get the twenty-first element, which clearly does not exist, thus the error. There are two solutions:
1. Enlarge the array to cover all indices that you need, or
2. Do not try to extract an index that does not exist: this could include using min to restrict the subscript value, or logical indexing, or an if statement as a special case.
What you choose depends on your algorithm, your requirements, how you want to code, etc.
The best choice would be to remove that loop altogether, and learn how to write vectorized code in MATLAB. This would fix several issues with the code, such as the bizarre incrementing of the loop variable within a for loop, and the reassignment of Tc(20) within the loop.
Note that you should avoid using i and j as loop variable names, as these are names of the inbuilt imaginary unit.
Try this:
num = 20;
x = 27;
Tc = 110;
for k = 2:num
Tc(k) = Tc(k-1) - (Tc(k-1)-x)/num;
end
Julia 2015년 3월 24일
num=20;
Tc0=110;
Tc(20)=27;
Tc(1)=109;
for i=2:num;
detaTc=(Tc0-Tc(20))/num;
Tc(i)=(Tc0- detaTc)
Tc0=Tc(i);
end
If you set Tc0=110 inside the loop it will always overwrite the vale Tc0=Tc(i).

Stalin Samuel 2015년 3월 24일
num=20;
for i=2:num;
Tc0=110;
Tc(20)=27;
Tc(1)=109;
detaTc=(Tc0-Tc(20))/num;
Tc(i)=(Tc0- detaTc)
Tc0=Tc(i);
i=i+1;
end
##### 댓글 수: 2없음 표시없음 숨기기
B 2015년 3월 24일
Thanx; the error msg has disappeared now,, but the loop is not functioning accurately.. I'm sure that I have done some mistakes there cz when I run the file, I should get a decreasing Tc: something similar to : Tc= 105,100,95,90,....,27
Stephen23 2015년 3월 24일
@stalin samuel: Note that you should avoid using i and j as loop variable names, as these are names of the inbuilt imaginary unit.

이 질문은 마감되었습니다.

### Community Treasure Hunt

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

Start Hunting!

Translated by