# Sort expression by numerical value of coefficient of two variables with indices

Consider this expression

qVector =
{0.333514 Subscript[η, 1] - 0.289181 Subscript[η, 2] -
0.0315191 Subscript[η, 3] - 0.000525409 Subscript[η, 4] -
0.000301152 Subscript[η, 5] + 0.671523 Subscript[μ, 1] -
0.591835 Subscript[μ, 2] - 0.0511302 Subscript[μ, 3] +
0.0120878 Subscript[μ, 4] + 0.0133259 Subscript[μ, 5]}


I want to sort it according to the value of the coefficients, and not to the "alphabetical" value.

Since this works:

Coefficient[qVector[[1, 1]], qVector[[1, 1, 2]]]
(* 0.33351 4*)


I thought that this should work:

SortBy[qVector[[1]], Coefficient[#, #[[2]]] &]


But it doesn't, I get:

 (* 0.333514 Subscript[η, 1]-0.289181 Subscript[η, 2]-0.0315191 Subscript[η, 3]-0.000525409 Subscript[η, 4]-0.000301152 Subscript[η, 5]+0.671523 Subscript[μ, 1]-0.591835 Subscript[μ, 2]-0.0511302 Subscript[μ, 3]+0.0120878 Subscript[μ, 4]+0.0133259 Subscript[μ, 5]  *)


What am I doing wrong?

Internally, Mathematica will enforce its canonical ordering of terms, but what you ask for can be done for display purposes. It will involve working with held forms.

Since I don't understand why you are dealing with a list of one item, I will work with the sum contained in the list.

sum =
0.333514 Subscript[η, 1] - 0.289181 Subscript[η, 2] -
0.0315191 Subscript[η, 3] - 0.000525409 Subscript[η, 4] -
0.000301152 Subscript[η, 5] + 0.671523 Subscript[μ, 1] -
0.591835 Subscript[μ, 2] - 0.0511302 Subscript[μ, 3] +
0.0120878 Subscript[μ, 4] + 0.0133259 Subscript[μ, 5];

Composition[HoldForm, Plus] @@ SortBy[HoldForm @@ sum, First]


The strategy is to wrap the terms of the sum in HoldForm, sort by the coefficients, and then change the head of the sorted held form to HoldForm[Plus[ ]] to restore the summing.

• Great, works nicely, thanks! – Santi Dec 27 '16 at 12:00