Info

This question is closed. Reopen it to edit or answer.

for loop help matlab error

1 view (last 30 days)
B
B on 24 Mar 2015
Closed: MATLAB Answer Bot on 20 Aug 2021
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!~

Answers (2)

Julia
Julia on 24 Mar 2015
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 Comments
Julia
Julia on 24 Mar 2015
How about this code?
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
Stalin Samuel on 24 Mar 2015
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 Comments
Stephen23
Stephen23 on 24 Mar 2015
@stalin samuel: Note that you should avoid using i and j as loop variable names, as these are names of the inbuilt imaginary unit.

Tags

Community Treasure Hunt

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

Start Hunting!

Translated by