Is there any way i can sort the following expression ?

a[k, l] b[i, j]

so that i would have:

b[i, j] a[k,l]

Mathematica does the ordering based on the heads. is there anyway to change it ?

  • $\begingroup$ To be clear: you are seeking a way to sort the elements of that expression based on the lexicographical ordering of the arguments to those elements ? $\endgroup$ – High Performance Mark Feb 7 at 15:33
  • $\begingroup$ @High Performance Mark i want to order the expression based on their arguments rather than the heads. so if i have a[m,n] b[i,j] c[k,l] i want it to be like b[i,j] c[k,l] a[m,n] $\endgroup$ – user49047 Feb 7 at 16:15
  • 1
    $\begingroup$ The expression you show here has head Times: spaces are interpreted as multiplication (use FullForm to check if you're unsure). Times is a symbol with the attribute Orderless, meaning that it will always sort its arguments in canonical order. The only way to have something close to what you want is Inactivate[b[i, j] a[k, l], Times] $\endgroup$ – Sjoerd Smit Feb 7 at 16:15
  • $\begingroup$ Inactive[Times] @@ SortBy[List @@ expr, First] $\endgroup$ – Bob Hanlon Feb 7 at 16:29

with the help of Bob Hanlon:

axx = HoldForm[
   NonCommutativeMultiply @@ 
    SortBy[List @@ (a[k, l] b[i, j]), First]] // ReleaseHold

axx //. NonCommutativeMultiply[a_, Y___] :> HoldForm[Times[a, Y]]
SortBy[Inactivate[a[m, n] b[i, j] c[k, l], Times], Function[x, #[[x]]]/@ Range[Length@#]&] /.
  Inactive[Times] -> HoldForm@*Times

b[i,j] c[k,l] a[m,n]


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.