for and while loop
1 次查看(过去 30 天)
显示 更早的评论
Hi
I am looking to run a while loop that solves a rootfinding problem for two initail values, stored in a matrix as described below. It should store the two solved coordiantes in xysolve.
The while loop works fine when running with ii = 1 or ii = 2 (indexing the two initial values) independtly.
However it does not work within the for loop, that I want to use to run the rootfinding for both initail values, one after the other.
Not sure what is the problem here.
Many thanks in advance for any help.
T
%% Solving
% Initial estimates are 2 2x1 vectors: [-10; 10] and [10;-10]
% These are stored together in 2x2 matrix xy
xy = [-10 10 ; 10 10];
iter = 0; imax=100; tol=0.001; err=tol;
xysolve = zeros(2,2)
for ii = 1:2
while iter <= imax && err >= tol
iter = iter + 1;
xy_new = xy(:,ii) - Jacob(xy(:,ii))\f(xy(:,ii));
err = norm(f(xy(:,ii)));
xy = [0 0 ; 0 0]
xy(:,ii) = xy(:,ii) + xy_new
xysolve = xy
end
end
采纳的回答
Rik
2021-1-21
You need to reset the error term and iteration count at the start of the for loop. Otherwise it will keep the previous values and immediately exit the while loop.
3 个评论
Rik
2021-1-21
You are wiping your initial value array as well by setting xy=zeros(2);. But otherwise, yes, this is what I meant.
As a further note: I would strongly suggest using the automatic indentation for readability. I would also suggest adding comments about what the code is doing.
更多回答(0 个)
另请参阅
类别
在 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!