Manipulating the elements of a list

Let's create some sample data

tab = Table[{i, j, k}, {i, -3, 3}, {j, -3, 3}, {k, -3, 3}];
ICs = Flatten[tab, 2];
Nt = Length[ICs];

A $3\times3$ system of equations

f = x^2 - 2*x + y^2 - z + 1;
g = x*y^2 - x - 3*y + y*z + 2;
h = x*z^2 - 3*z + y*z^2 + x*y;

and its numerical solution

sol0 = NSolve[{f == 0, g == 0, h == 0}, {x, y, z}, Reals]

Now let's assign an integer number to each solution

rules = Rule @@@ Transpose[{sol0[[;; , ;; , 2]], Range[Length[sol0]]}]

Finally we define an iterative procedure

data = {};
For[j = 1, j <= Nt, j++,
x0 = ICs[[j, 1]];
y0 = ICs[[j, 2]];
z0 = ICs[[j, 3]];
sol = FindRoot[{f == 0, g == 0, h == 0}, {x, x0}, {y, y0}, {z, z0}];
xf = x /. sol[];
yf = y /. sol[];
zf = z /. sol[];
AppendTo[data, {x0, y0, z0, xf, yf, zf}]
]

For some initial conditions the FindRoot works well, while for some other it fails to converge to one of the five solutions. The results are stored to data list.

I would like to obtain a new table, data2 in which the first three elements x0,y0,z0 to be the same as in data, while the forth element to be the corresponding integer according to the above rule. If xf,yf,zf do match with one of the five solutions then the new list should contain the corresponding integer on the forth column. If they do not match a 0 should be assigned. How can I achieve this?

A minor issue: I know that FindRoot uses the Newton-Raphson method in order to solve a system of equations. Is possible to include in data list the number of iterations needed by the Newton-Raphson iterative method for converging to a solution?

Many thanks in advance!

sol0 = NSolve[{f, g, h}, {x, y, z}, Reals]

rules = MapIndexed[# -> #2[] &, {x, y, z} /. sol0]

data = Quiet[
Function[{x0, y0, z0}, {x0, y0, z0, x, y, z} /.
FindRoot[{f, g, h}, {x, x0}, {y, y0}, {z, z0}]] @@@ ICs]

data2 = Flatten /@
Replace[Partition[#, 3] & /@
data, ({l1_, l2_} /; Chop@Total[(l2 - #)^2] == 0 :> {l1, #2} & @@@ rules)~
Join~{{l1_, l2_} :> {l1, 0}}, {1}]

As to the "minor" issue, start from checking the document of StepMonitor and EvaluationMonitor.

• Just out of curiosity, why do you create the initial data list in a different way? Is it because the For loop is a little bit slow? – Vaggelis_Z Feb 29 '16 at 12:51
• @Vaggelis_Z Just for conciseness and… fun :D . Though For is slow, it's not a big deal in your case. – xzczd Feb 29 '16 at 13:07