loop until condition met
2 次查看(过去 30 天)
显示 更早的评论
im trying to create a loop until a certain condition exists by using the results at the end of each loop to calculate the next iteration. I've shown part of the code below. Iteration to terminate when Va = Vo = Vn.
Vo = [30 15 13 10];% initial V old to calc Re and f.
Va=zeros(size(Vo));
Vn=zeros(size(Vo));
%
while ~all([Va==Vo,Vo==Vn])
%
Re1 = (D(1).*Vo(1)) / nu;
%
Re2 = (D(2).*Vo(2)) / nu;
%
Re3 = (D(3).*Vo(3)) / nu;
%
Re4 = (D(4).*Vo(4)) / nu;
%
A = [Matrix];
b = [Matrix];
Vn = A\b;% solves four unknowns at A\b
%
for i = 1:4
Va(i) = (alpha * Vn(i)) + ((1-alpha) * Vo(i));
Vo(i) = Va(i); %Used as Vo for each in next iteration.
end
end
0 个评论
采纳的回答
kjetil87
2013-9-1
编辑:kjetil87
2013-9-1
Vo = [30 15 13 10];% initial V old to calc Re and f.
MaxIter=1e10;
%
Cntr=0;
while true
Cntr=Cntr+1;
%
Re1 = (D(1).*Vo(1)) / nu;
%
Re2 = (D(2).*Vo(2)) / nu;
%
Re3 = (D(3).*Vo(3)) / nu;
%
Re4 = (D(4).*Vo(4)) / nu;
%
A = [Matrix];
b = [Matrix];
Vn = A\b;% solves four unknowns at A\b
%
for i = 1:4
Va(i) = (alpha * Vn(i)) + ((1-alpha) * Vo(i));
end
if all(abs(Va-Vn(1:4))<1e-10) && all(abs(Va-Vo)<1e-10)
break;
end
if Cntr==MaxIter % add this to avoid being stuck if there is no solution.
break;
end
Vo=Va;
end
0 个评论
更多回答(1 个)
kjetil87
2013-9-1
A while loop is what you are looking for it seems.
while ~all([Va==Vo,Vo==Vn])
%your code
end
5 个评论
kjetil87
2013-9-1
The error is because Va and Vn is not defined yet. Either pre define or use the answer below. Also note the different compare method used, because i doubt the 3 vectors will be EXACTLY equal so therefor it is better to compare using a threshold.
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Loops and Conditional Statements 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!