# How to pick elements of a matrix in increasing numerial value order for a loop operation

I have a 3X3 matrix and want to select its elements in order of their increasing numerical value for a loop operation. How can I do it.

For example if

x = {{1, 4, 6}, {2, 5, 8}, {11, 14, 16}},


I want a use script which can feed its elements in increasing numerical values (1, 2, 4, ...etc) in a "For" operation along with their i&j values. For[Xmin, Xmax, X++, Print[X, i, j]] should be able to give

{1, 1, 1}
{2, 2, 1}
{4, 2, 1}

----
etc.


I want to know what script I should use for "X" thanks

• Why should it have to be a loop? SortBy[Flatten[MapIndexed[List, {{1, 4, 6}, {2, 5, 8}, {11, 14, 16}}, {2}], 1], First] – J. M.'s discontentment Sep 23 '17 at 17:43
• To get your desired output from @J.M.'s comment, replace List with Flatten@*List. – jjc385 Sep 23 '17 at 17:48
• Re avoiding loops, see this answer, especially point (3). – jjc385 Sep 23 '17 at 18:03
• My problem might not be making much sense as I posted only part of it. Actually I have two 3X3 (say A & B) matrices. I want to perform a loop operation on the system such that elements of matrix A in the order of increasing numerical values are compared with the corresponding element of B such that if for the element [i, j] If A[i j] < B[i, j] -> next higher magnitude A[i, j] is selected Or if A[i j] > B[i, j], a parameter m is increased in its value by 1, which will be used to stimulate the next step. Hope it helps in understanding my problem. Thanks – user49535 Sep 23 '17 at 19:10
• Consider asking that as a different question, tho I suspect that this is an XY problem. – J. M.'s discontentment Sep 23 '17 at 19:11

m = {{1, 4, 6}, {2, 5, 8}, {11, 14, 16}}
Sort@Catenate@MapIndexed[List[#1, Sequence @@ #2] &, m, {2}]


Edit: following jjc's suggestion, you could alternatively

Sort@Catenate@MapIndexed[Flatten@*List, m, {2}]


It is shorter but I assume less efficient, since it creates and then flattens a list.

x = {{1, 4, 6}, {2, 5, 8}, {11, 14, 16}};
SortBy[{x[[##]], Sequence@##} & @@@
Tuples[Range /@ Dimensions[x]], First]


yields:

(* {{1, 1, 1}, {2, 2, 1}, {4, 1, 2}, {5, 2, 2}, {6, 1, 3}, {8, 2,
3}, {11, 3, 1}, {14, 3, 2}, {16, 3, 3}}*)