1

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

J. M.'s missing motivation
  • 124,525
  • 11
  • 401
  • 574
user49535
  • 1,225
  • 6
  • 9
  • 1
    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 missing motivation Sep 23 '17 at 17:43
  • 1
    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 missing motivation Sep 23 '17 at 19:11
  • Ok, I can post the complete problem as a separate Q. Thanks – user49535 Sep 23 '17 at 19:19

2 Answers2

1
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.

Alan
  • 13,686
  • 19
  • 38
0
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}}*)
ubpdqn
  • 60,617
  • 3
  • 59
  • 148