How do I fix an infinite loop?

9 views (last 30 days)
I tried using Simpson's 1/3rd rule for multiple segments. Can someone please tell me why this code isn't working?
%Specific Heat f(T) = a+bT+CT.^2
function [Cp]=f(T,a,b,c)
Cp=a+(b*T)+(c*(T^2));
end
a=input('a = ');
b=input('b = ');
c=input('c = ');
T1=input('Initial Temperature T1 = ');
T2=input('Final Temperature T2 = ');
n=input('Number of divisions ');
h=abs(T2-T1)/n;
sum2=0;
sum3=0;
for i=(T1+h):h:(T2-h)
sum1=f(T1,a,b,c)+f(T2,a,b,c);
while even(i)==1
sum2=sum2+f(i,a,b,c);
end
while even(i)==0
sum3=sum3+f(i,a,b,c);
end
sum=sum1+(2*(sum2))+(4*(sum3));
Value=(h/3)*sum;
disp(Value);
end

Accepted Answer

Walter Roberson
Walter Roberson on 26 Nov 2017
You have
while even(i)==1
sum2=sum2+f(i,a,b,c);
end
We do not know what the code for even() is, but in order for that loop to terminate, something in the body of the loop must trigger even(i) to become false. You do not change the argument, i, in the body of the loop, only sum2, so in order for that code not to be an infinite loop, the missing function even() would need to somehow be examining sum2 .
I speculate that you do not want a while loop there, that you just want an if
  3 Comments
NN
NN on 20 Nov 2019
Hi Sir,
I am using if conditions in simulink with logical operators and i experince same problem , matlab hangs after running the simulation.I doubt if the loop goes to inifinity and if so how can i correct it in simulink .My model is a power system model and if condition has to check net power at ac grid continuosly during simulation time.can i add any other block in simulink itself to solve this isissue or need to write program
Walter Roberson
Walter Roberson on 20 Nov 2019
I recommend that you create a new Question and post your model there.

Sign in to comment.

More Answers (1)

Roger Stafford
Roger Stafford on 26 Nov 2017
You are using the 'even' function on temperatures instead of index values. You should probably have something like:
h = (T2-T1)/n;
T = linspace(T1,T2,n+1); % n must be even
Value = h/3*(f(T1,a,b,c)+4*sum(f(T(2:2:n),a,b,c)) ...
+2*sum(f(T(3:2:n-1),a,b,c))+f(T2,a,b,c));

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!