MATLAB: I keep getting an error saying index exceeds matrix dimensions

errorindexingmatrix

if true
% code
end
n=1;
t(1)=0;
T(1)=50;
Tout=375;
k=0.0035;
time=[0.0,0.5,2.0];
temps=[106,96,102];
h=30;
while T<160
n=n+1;
slope=-k*(T(n)-Tout);
t(n+1)=t(n)+h;
T(n+1)=T(n)+h*slope;
end

Best Answer

Initialize n at 0:
n=0;
t(1)=0;
T(1)=50;
Tout=375;
k=0.0035;
time=[0.0,0.5,2.0];
temps=[106,96,102];
h=30;
while T<160
n=n+1;
slope=-k*(T(n)-Tout);
t(n+1)=t(n)+h;
T(n+1)=T(n)+h*slope;
end
or increase n later in the loop:
n=1;
t(1)=0;
T(1)=50;
Tout=375;
k=0.0035;
time=[0.0,0.5,2.0];
temps=[106,96,102];
h=30;
while T<160
slope=-k*(T(n)-Tout);
t(n+1)=t(n)+h;
T(n+1)=T(n)+h*slope;
n=n+1;
end