2
$\begingroup$

Let's hope I'm calling it well, I have this vector, or matrix, now I really don't know what it is

{
{{1,0.4,0,0,0,0},{2,0.5,0,0,0,0},{3,0.2,0,0,0,0}},
{{3,0.2,1,5.5686,23.618,1},{2,0.5,0,0,0,0},{1,0.4,0,0,0,0}}
{{2,0.2,0,5.5686,23.618,1},{3,0.5,0,0,0,0},{1,0.4,0,0,0,0}}
}

I want to sort the second level vectors, in a particular manner that the smallest vectors are ordered by their first element, so they all follow the 1,2,3 order in the first element:

{
{{1,0.4,0,0,0,0},{2,0.5,0,0,0,0},{3,0.2,0,0,0,0}},
{{1,0.4,0,0,0,0},{2,0.5,0,0,0,0},{3,0.2,1,5.5686,23.618,1}}
{{1,0.4,0,0,0,0},{2,0.2,0,5.5686,23.618,1},{3,0.5,0,0,0,0}}
}

I was trying different ways, the last one being the following that I found in another question, but it only sorts a common matrix of the type:

 { { }, { } }

But not of the type:

 { { { } , { } } , { { } , { } } }

This is the code:

For[i = 1, i <= Length[BigVector], i++, 
  SortBy[BigVector[[i]], #[[1]] &]];
$\endgroup$

1 Answer 1

2
$\begingroup$
mat = {{{1, 0.4, 0, 0, 0, 0}, {2, 0.5, 0, 0, 0, 0}, {3, 0.2, 0, 0, 0, 0}},
       {{3, 0.2, 1, 5.5686, 23.618, 1}, {2, 0.5, 0, 0, 0, 0}, {1, 0.4, 0, 0, 0, 0}} , 
       {{2, 0.2, 0, 5.5686, 23.618, 1}, {3, 0.5, 0,  0, 0, 0}, {1, 0.4, 0, 0, 0, 0}}};

You can use

#[[Ordering[#]]] & /@ mat

or

Sort /@ mat

or

Map[Sort, mat] 

all give

(*  { {{1, 0.4, 0, 0, 0, 0}, {2, 0.5, 0, 0, 0, 0}, {3, 0.2, 0, 0, 0,  0}},
      {{1, 0.4, 0, 0, 0, 0}, {2, 0.5, 0, 0, 0, 0}, {3, 0.2, 1, 5.5686, 23.618, 1}}, 
      {{1, 0.4, 0, 0, 0, 0}, {2, 0.2, 0, 5.5686,  23.618, 1}, {3, 0.5, 0, 0, 0, 0}}} *)
$\endgroup$
2
  • $\begingroup$ Wow, I did't now it was that simple, thanks! $\endgroup$ Nov 12, 2014 at 1:03
  • $\begingroup$ Jose, my pleasure. Welcome to mma.se. $\endgroup$
    – kglr
    Nov 12, 2014 at 1:08

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

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