MATLAB Answers

0

A code that freezes Matlab on 'busy' at some values.

Asked by Nawaf Alshehri on 17 May 2019
Latest activity Commented on by Raj
on 20 May 2019 at 3:51
Hi there,
I have the following code in matlab
clc
Pr=input('Please enter the reduced pressure Pr = ');
Tr=input('Please enter the reduced temperature Tr = ');
A1=0.3265;A2=-1.07;A3=-0.5339;A4=0.01569;A5=-0.05165;A6=0.5475;A7=-0.7361;A8=0.1844;A9=0.1056;A10=0.6134;A11=0.7210;
Z1=0.01;
Dr=(0.27*Pr)/(Z1*Tr);
Z=1+(A1+(A2/Tr)+(A3/Tr^3)+(A4/Tr^4)+(A5/Tr^5))*Dr+(A6+(A7/Tr)+(A8/Tr^2))*Dr^2-A9*((A7/Tr)+(A8/Tr^2))*Dr^5+A10*(1+(A11*Dr^2))*(Dr^2/Tr^3)*exp(-A11*Dr^2);
while abs(Z-Z1)>0.01
Z1=Z;
Dr=(0.27*Pr)/(Z1*Tr);
Z=1+(A1+(A2/Tr)+(A3/Tr^3)+(A4/Tr^4)+(A5/Tr^5))*Dr+(A6+(A7/Tr)+(A8/Tr^2))*Dr^2-A9*((A7/Tr)+(A8/Tr^2))*Dr^5+A10*(1+(A11*Dr^2))*(Dr^2/Tr^3)*exp(-A11*Dr^2);
end
fprintf('Z factor = %4.5f\n',Z)
when I enter some values for the Tr and Pr, the code works just fine.
but it freezes at some points like Pr=8 Tr=1.05
I use Matlab 2019
Can someone please tell me how to solve this issue?

  0 Comments

Sign in to comment.

1 Answer

Answer by Raj
on 17 May 2019
Edited by madhan ravi
on 17 May 2019

The code is not actually freezing and there is no issue with MATLAB. Its just the way your code is written. Try putting breakpoints and going to debug mode. You'll see that for some combinations of Pr and Tr, the while loop exit condition is not getting satisfied so the execution just keeps on looping there. One way to handle this is to break the loop after certain amount of time beyond which you know that the loop has hung. You can do this by adding tic toc condition like this:
while abs(Z-Z1)>0.01
tic
Z1=Z;
Dr=(0.27*Pr)/(Z1*Tr);
Z=1+(A1+(A2/Tr)+(A3/Tr^3)+(A4/Tr^4)+(A5/Tr^5))*Dr+(A6+(A7/Tr)+(A8/Tr^2))*Dr^2-A9*((A7/Tr)+(A8/Tr^2))*Dr^5+A10*(1+(A11*Dr^2))*(Dr^2/Tr^3)*exp(-A11*Dr^2);
xyz=toc
if xyz==1 % Say you want to exit loop after 1 seconds
break
end
end

  2 Comments

There are at least two problems with this code.
The first is that this will exit if the computation of Dr and Z for one iteration takes exactly 1 second. That doesn't strike me as what you intended, which is to stop if the while loop as a whole has been running for 1 second, not just one iteration.
The second is that you don't want to check that the loop has taken exactly 1 second. If it has taken 1 second or longer you want to stop.
I'd probably write this like:
tic;
while abs(Z-Z1) > 0.01 && toc <= 1
Z1=Z;
Dr=(0.27*Pr)/(Z1*Tr);
Z=1+(A1+(A2/Tr)+(A3/Tr^3)+(A4/Tr^4)+(A5/Tr^5))*Dr+...
(A6+(A7/Tr)+(A8/Tr^2))*Dr^2-A9*((A7/Tr)+...
(A8/Tr^2))*Dr^5+A10*(1+(A11*Dr^2))*(Dr^2/Tr^3)*exp(-A11*Dr^2);
end
This will stop if abs(Z-Z1) > 0.01 is false or toc returns a value greater than 1.
+1.Accepted. Thanks!!

Sign in to comment.