In nested for-loops, how and where should I set the counting index (indices?) correctly, for doing numerical root-finding using fsolve?
이전 댓글 표시
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
Matt J
2020년 9월 25일
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.
채택된 답변
추가 답변 (0개)
카테고리
도움말 센터 및 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!