In nested for-loops, how and where should I set the counting index (indices?) correctly, for doing numerical root-finding using fsolve?
Show older comments
Hi,
Let's say I have a function, f, that maps R^3 to R^3, and I want to find its multivariable roots numerically, using fsolve.
What's a good way to use the counting index, i, in the loops?
For instance, if f(x,y,z) = ( f_1(x,y,z), f_2(x,y,z), f_3(x,y,z) ), and I want to solve f = (0,0,0), then I could write nested for-loops that do something like this:
for x_guess = linspace(-10,10,10) % first, fix a guess for x
for y_guess = linspace(-10,10,10) % now for a fixed x, also fix a guess for y
for z_guess = linspace(-10,10,10) % now for a fixed x and y, check all values of z, before fixing a new x and y
i = ...
end
end
end
[ multivariable_roots, FVAL, EXITFLAG, OUTPUT, JACOB ] = fsolve( f, [x_guess, y_guess, z_guess] )
Where's a good place to put the counting index? At the innermost loop? Could I do so at the outermost loop?
My mentor showed me a code that uses the counting index in the innermost loop (the code structure that I provided above), but I currently don't understand it, so I'd like to write my own nested for-loops in order to understand what it does.
Also, would using more than one counting index be helpful? I'm thinking of using counting indices i, j, k, if it makes the nested for-loops easier to understand. For instance, in a double summation, we would typically fix i and sum through j -- and then fix another i and sum through j again, etc. Could I do something analogous in nested for-loops? I think I might actually prefer using a different counting index for each loop, since things might look more explicit that way.
Thanks,
2 Comments
Matt J
on 25 Sep 2020
Could I do something analogous in nested for-loops?
Every for-loop has a loop index (otherwise, what action is it performing), so if you are going to use 3 loops, you will inevitably have 3 loop indices.
Accepted Answer
More Answers (0)
Categories
Find more on Loops and Conditional Statements in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!