for and while loop
1 vue (au cours des 30 derniers jours)
Afficher commentaires plus anciens
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 commentaires
Réponse acceptée
Rik
le 21 Jan 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 commentaires
Rik
le 21 Jan 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.
Plus de réponses (0)
Voir également
Catégories
En savoir plus sur Loops and Conditional Statements dans Help Center et File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!