How do I fix an infinite loop?

1 vue (au cours des 30 derniers jours)
Prakriti Gupta
Prakriti Gupta le 26 Nov 2017
Commenté : Walter Roberson le 20 Nov 2019
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

Réponse acceptée

Walter Roberson
Walter Roberson le 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 commentaires
NN
NN le 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 le 20 Nov 2019
I recommend that you create a new Question and post your model there.

Connectez-vous pour commenter.

Plus de réponses (1)

Roger Stafford
Roger Stafford le 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));

Catégories

En savoir plus sur Simulink dans Help Center et File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by