How do I fix an infinite loop?
조회 수: 1 (최근 30일)
이전 댓글 표시
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
채택된 답변
Walter Roberson
2017년 11월 26일
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
NN
2019년 11월 20일
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
추가 답변 (1개)
Roger Stafford
2017년 11월 26일
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));
댓글 수: 0
참고 항목
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!