How do I fix an infinite loop?
1 回表示 (過去 30 日間)
古いコメントを表示
Prakriti Gupta
2017 年 11 月 26 日
コメント済み: Walter Roberson
2019 年 11 月 20 日
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
Walter Roberson
2019 年 11 月 20 日
I recommend that you create a new Question and post your model there.
その他の回答 (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!