# Loop never stops?

1 view (last 30 days)
Amanda Liu on 16 Jun 2021
Commented: Amanda Liu on 16 Jun 2021
Why does my loop never stops after I assign k1 & k2 as symbolic variables?
n=10;
T=sym(zeros(n,n));
T(1,:) = 410; % Top
T(end,:) = 420; % Bottom
T(:,1) = 400; % Left
T(:,end) = 400; % Right
T_old = T;
for k = 1:20 %time steps
for j = 2: (n-1)
for i = 2: (n-1)
%k1 = 0.02; k2=0.33;
syms k1 k2
T(i,j) = T_old(i,j)*(1-2*k1-2*k2)+k1*(T_old(i-1,j)+T_old(i+1,j))+k2*(T_old(i,j-1)+T_old(i,j+1));
end
end
T_old = T;
end
##### 2 CommentsShowHide 1 older comment
Amanda Liu on 16 Jun 2021
Yes as I have 2 different values of k1 and of k2.

Walter Roberson on 16 Jun 2021
The code does finish. It just takes a long time. You are building some complicated expressions. You can improve performance by putting in an expand() call:
On my system, execution time is about 22 seconds, but on the demonstration system here it is over 55 seconds so I cannot show you the result.
tic
n = 10;
T=sym(zeros(n,n));
T(1,:) = 410; % Top
T(end,:) = 420; % Bottom
T(:,1) = 400; % Left
T(:,end) = 400; % Right
T_old = T;
syms k1 k2
for k = 1:20 %time steps
for j = 2: (n-1)
for i = 2: (n-1)
T(i,j) = expand(T_old(i,j)*(1-2*k1-2*k2)+k1*(T_old(i-1,j)+T_old(i+1,j))+k2*(T_old(i,j-1)+T_old(i,j+1)));
end
end
T_old = T;
end
toc
T(1:5,1:5)
Tn = subs(T, {k1, k2}, {0.02, 0.33});
Tn(1:5,1:5)
vpa(Tn,5)
##### 2 CommentsShowHide 1 older comment
Amanda Liu on 16 Jun 2021
Thank you for replying. I will proceed with this method and get back to you soon.

R2021a

### Community Treasure Hunt

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

Start Hunting!