For Loop nested within a while loop, run until condition is met

My goal is to run an equation until my convergence criteria is met, basically do itterations until I am within some range of error. My code looks liek this
%% Model Cells
% Boundary conditions is head1 = 3 & head12=1
head = zeros (1,12); % Established a matrix of data
head(1)=3; % Setting boundary conditions
head(12)=1;
depth = [0.00,0.35,0.70,1.05,1.40,1.75,2.10,2.45,2.80,3.15,3.50,3.85];%for future plotting purposes
headold = zeros(1,12);
% Loop iteration & Stop iteration
x = ones(1,12);
cc = x*.001;
while headold-head<cc % solving for head until convergence criteria is met
headold = head;
% head = headold+1;
% headold+2 = headold+1;
for i=2:11
head(i)=(head(i-1)+head(i+1))/2; %solving for head 1 time
end
end
The result of this is a never ending matlab solution, however when I pause this I get the anser I want .

 采纳的回答

This lines actually means: "loop if condition is met"
while headold-head<cc % solving for head until convergence criteria is met
Use this
tol = abs(head-headold);
while max(tol)>0.001 % solve if max(tolerance) > 0.001
%% ...
tol = abs(head-headold);
end

5 个评论

Perfect, thank you! Why though was mine not correct? I am just trying to understand why its wrong.
Your while-loop is defined as while headold-head<cc. If you execute headold-head<cc you'll find that it produces a vector. The conditional expression should evaluate to a scalar logical value, not a vector. When the expression evaluates to a vector, all of the elements of the vector must be true for the while-loop to continue.
Here's a demo. Test the two x vectors.
x = logical([1 1 1 1 1]);
% x = logical([1 1 1 1 0]);
while x
disp('In while-loop')
x = false;
end
  • Why though was mine not correct?
Because headold-head gives negative values only (cc is positive)
Try
while headold-head<cc % solving for head until convergence criteria is met
headold = head;
% head = headold+1;
% headold+2 = headold+1;
for i=2:11
head(i)=(head(i-1)+head(i+1))/2; %solving for head 1 time
end
plot(headold-head)
pause(0.1)
end
@dovara, but headold-head<cc will still produce a vector which is the problem I mentioned above.

请先登录,再进行评论。

更多回答(0 个)

类别

帮助中心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!

Translated by