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!