MATLAB: How to determine number of iterations for steady state

MATLABsteady state

I have a problem where I'm using a code to do the heat equation, i want to get the steady state, i have found it but it was random to find it. How can I make my code break when it reaches steady state?
L = 1;
n = 30;
dx = L/(n-1);
k = 1/(1.5*10^6);
K = 0.3;
dt = K*(dx^2/k);
T1 = zeros(1,n);
T2 = zeros(1,n);
T1(end)= 0;
T2(1) = -10;
for i=1:1000
for j = 2:n-1
T2(j) = T1(j)+ (dt*k/dx^2)*(T1(j+1) - 2*T2(j)+ T2(j-1));
end
T1 = T2;
end
plot(T1)

Best Answer

I am not sure how you are saving the values inside the for-loop, but it seems that you are trying to integrate a function. You can check if it is the steady-state when the absolute change in value becomes less than a threshold value. For example,
L = 1;
n = 30;
dx = L/(n-1);
k = 1/(1.5*10^6);
K = 0.3;
dt = K*(dx^2/k);
T1 = zeros(1,n);
T2 = zeros(1,n);
T1(end)= 0;
T2(1) = -10;
for i=1:1000
for j = 2:n-1
dT = (dt*k/dx^2)*(T1(j+1) - 2*T2(j)+ T2(j-1));
T2(j) = T1(j) + dT;
if abs(dT) < 1e-3 % threshold reached.
break
end
end
T1 = T2;
end
plot(T1)