for and while loop
1 visualización (últimos 30 días)
Mostrar comentarios más antiguos
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
3 comentarios
Respuesta aceptada
Rik
el 21 de En. de 2021
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 comentarios
Rik
el 21 de En. de 2021
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.
Más respuestas (0)
Ver también
Categorías
Más información sobre Loops and Conditional Statements en Help Center y File Exchange.
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!