0

In the last line of code, I´m trying to order the matrix by the first column.

I want to store in the Array t2tlistsorted ( 100 x 3 ), but I can´t.

t = {
  {{2, 1}, {5, 2}},
  {{7, 1}, {9, 4}},
  {{9, 2}, {6, 6}},
  {{5, 4}, {2, 3}},
  {{4, 5}, {7, 9}},
  {{8, 5}, {2, 4}},
  {{3, 7}, {7, 7}},
  {{4, 8}, {1, 10}},
  {{3, 10}, {10, 7}},
  {{9, 10}, {9, 8}}
  }
(* t[[i,j,k]    i\[Rule]tramo Nºi    j\[Rule] \
1=Inicio=Pick-Up  2=Fin=Drop-Off     k\[Rule] 1ª o 2ª componente (es \
decir x ó y) *)

Array[t2t, {10, 10}]
Array[t2tlist, {100, 3}]
Array[t2tlistsorted, {100, 3}]

For[i = 1, i <= 10, i++,
 For[j = 1, j <= 10, j++,
  If[i != j,
   t2t[i, j] = 
    Sqrt[  (    t[[j, 1, 1]] - t[[i, 2, 1]]      )^2          +    ( 
        t[[j, 1, 2]] - t[[i, 2, 2]]      )^2    ], t2t[i, j] = Infinity
   (* Calcualmos los Kilometros para ir del tramo i al tramo j, 
   para lo que recurrimos a la raiz cuadrada de la suma de los \
cuadrados de la diferencia entre el principio(1) del tramo=
   trip j   y el fin (2) del tramo=trip i *)
   ]
  ]
 ]
For[i = 1, i <= 10, i++,
 For[j = 1, j <= 10, j++,
  t2tlist[10 (i - 1) + j, 1] = t2t[i, j];
       t2tlist[10 (i - 1) + j, 2] = i;
       t2tlist[10 (i - 1) + j, 3] = j;
  ]
 ]
t2tlistsorted = SortBy[t2tlist, First]
(*SortBy[t2tlist,First] *)

Can you correct my fault?

In this image you can see the output lines

m_goldberg
  • 107,779
  • 16
  • 103
  • 257
Mika Ike
  • 3,241
  • 1
  • 23
  • 38
  • 1
    Doesn't give you SortBy[t, First] the desired output? Btw. for me it is not clear what t2t and so on is. – partial81 Jun 25 '13 at 15:05
  • @partial81 , t2t is an array 10 x 10. t2tlist is an array with the data in t2t and the indexes (i,j). So I want to sort t2tlists by the first column (original data in t2t.) – Mika Ike Jun 25 '13 at 17:04

1 Answers1

2

The problem is that t2list is not a list and therefore cannot be sorted. t2list is a symbol for which you have created lots of DownValues.

The solution is to use Array to create a list of the values, and then sort that list:

t2tlistsorted = SortBy[Array[t2tlist, {100, 3}], First]

Using lists throughout

You would be better off using lists for t2t and t2tlist, instead of working with downvalues in nested For loops. For example:

t = {{{2, 1}, {5, 2}}, {{7, 1}, {9, 4}}, {{9, 2}, {6, 6}}, {{5, 
     4}, {2, 3}}, {{4, 5}, {7, 9}}, {{8, 5}, {2, 4}}, {{3, 7}, {7, 
     7}}, {{4, 8}, {1, 10}}, {{3, 10}, {10, 7}}, {{9, 10}, {9, 8}}};

t2t = Table[{If[i != j, 
     Sqrt[(t[[j, 1, 1]] - t[[i, 2, 1]])^2 + (t[[j, 1, 2]] - t[[i, 2, 2]])^2],
       Infinity], i, j}, {i, 10}, {j, 10}];

t2tlist = Flatten[t2t, 1];   
t2tlistsorted = SortBy[t2tlist, First]
Simon Woods
  • 84,945
  • 8
  • 175
  • 324