Why do I have a never ending loop ?
Show older comments
Not sure why my loop continues? Solving a diffusion equation for context. Continues to print out time but should stop when conditions are met.
% Define constraints
alpha = 0.001; % cm^2/s
height = 2; % cm
dx = 0.1; % cm
dt = 0.1; % s
% Boundary conditions
Tbottom = 130; % C degrees
Tcondition=60; %degrees C
% Grid spacing
npoints = int32(height/dx)+1;
% Mesh
T=ones(1,npoints)*4.0; %initial temp is 4
disp(T)
time=0;
condition=true;
while condition
time=time+dt;
fprintf('Current Time is: %f\n', time);
Tnew=ones(1,npoints);
T(1)=Tbottom;
for i=2:npoints-1
Tnew(i)=(T(i))+alpha*dt/dx/dx * (T(i+1)+T(i-1)-2*T(i));
end
i=npoints-1;
Tnew(i)=T(i)-alpha*dt/dx/dx * (T(i)-T(i-1));
Tmin=inf;
for i=1:npoints
T(i)=Tnew(i);
if T(i)<Tmin
Tmin=T(i);
end
end
if Tmin>Tcondition
condition=false;
end
end
disp(T);
3 Comments
Which boundary condition did you try to set at x = height ?
In your code, your work with T = 4, and you set a strange update at x = height - dx:
i=npoints-1;
Tnew(i)=T(i)-alpha*dt/dx/dx * (T(i)-T(i-1));
And note that you never set Tnew(1) to a reasonable value in the while-loop.
Jalyn-Rose
on 8 Mar 2024
Torsten
on 8 Mar 2024
To answer your question:
Your while loop never stops because Tnew(1) is always 1 from the setting Tnew=ones(1,npoints);, thus < Tcondition.
Accepted Answer
More Answers (0)
Categories
Find more on Loops and Conditional Statements in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!