3
$\begingroup$

I have a list of variables, both constant and functions of an independent variable, including derivatives. I'd like to sort these by the variable name, rather than the derivative order. For example, the default Sort gives:

Sort[{x[t], x'[t], x''[t], y[t], y'[t], y''[t],a}]
{a, x[t], y[t], x'[t], y'[t], x''[t], y''[t]}

whereas I'd like to have all the derivatives of one variable clustered together:

{a, x[t], x'[t], x''[t], y[t], y'[t], y''[t]}

I'm sure there is a way to write an ordering function to do this, but I can't figure out how to do it.

$\endgroup$
1
  • 4
    $\begingroup$ A judicious use of SortBy[] ought to work… $\endgroup$ Aug 12, 2015 at 9:12

1 Answer 1

9
$\begingroup$

As suggested in the comments, SortBy should work. For example you could do

f[Derivative[_][x_][_]] := x
f[x_[_]] := x
f[x_] := x

SortBy[{a, x[t], y[t], x'[t], y'[t], x''[t], y''[t]}, f]

One should check how robust this solution is though.

Edit

And a more compact way of writing f is

f[Derivative[_][x_][_] | x_[_] | x_] := x
$\endgroup$

Your Answer

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

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