1
$\begingroup$

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

$\endgroup$
  • 1
    $\begingroup$ Why should it have to be a loop? SortBy[Flatten[MapIndexed[List, {{1, 4, 6}, {2, 5, 8}, {11, 14, 16}}, {2}], 1], First] $\endgroup$ – J. M. will be back soon Sep 23 '17 at 17:43
  • 1
    $\begingroup$ To get your desired output from @J.M.'s comment, replace List with Flatten@*List. $\endgroup$ – jjc385 Sep 23 '17 at 17:48
  • $\begingroup$ Re avoiding loops, see this answer, especially point (3). $\endgroup$ – jjc385 Sep 23 '17 at 18:03
  • $\begingroup$ 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 $\endgroup$ – user49535 Sep 23 '17 at 19:10
  • $\begingroup$ Consider asking that as a different question, tho I suspect that this is an XY problem. $\endgroup$ – J. M. will be back soon Sep 23 '17 at 19:11
1
$\begingroup$
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.

$\endgroup$
0
$\begingroup$
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}}*)
$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.