[Mathematica 6.0+] Preserving order of variables

  1. Hepth

    Hepth 499
    Gold Member

    Is there a way to set Mathematica so that it preserves the order of variables.
    i.e. I put:

    F[x_] = A B x
    F[a]
    output : aAB

    where I would want it: ABa

    Thanks.
     
  2. jcsd
  3. CompuChip

    CompuChip 4,299
    Science Advisor
    Homework Helper

    I am having the same problem.
    The best solution I have found in general is using NonCommutativeMultiply:
    F[x_] := A ** B ** x
    although you usually have to define lots of other stuff to get everything working out as you want.
    In some cases (like where A and B are explicitly defined matrices) you can use matrix multiplication
    F[x_] := A . B . x
    or a function
    F[x_] := AB[x]

    Do you have anything specific in mind?
     
  4. Hepth

    Hepth 499
    Gold Member

    I just have a long string of things that could either be matrices or vectors or scalars or tensors or etc. I'm trying to do some simplifications and then use the output. Its nothing special, I just need to preserve order. I'm not doing any REAL products (like inner, outer, contractions, etc) just representative products. If I define everything as matrices/vectors etc then it'll try to simplify it which i don't want. It needs to stay symbolic, yet perform basic distribution multiplication.

    I guess I'll try the noncommutative, that should work.
    Thanks!
     
  5. CompuChip

    CompuChip 4,299
    Science Advisor
    Homework Helper

    If you want distributivity, you probably want to define something like
    Code (Text):

    ExpandNCM[x_] := x //. {
       NonCommutativeMultiply[a__, b_ + c_, d__] :> a ** b ** d + a ** c ** d
       }
     
    So that, for example,
    Code (Text):

    a ** (b + c) ** d // ExpandNCM
     
    gives
    Code (Text):
    a ** b ** d + a ** c ** d
    .

    By the way, you can also try
    Code (Text):
    ClearAttributes[Times, Orderless]
    but I don't think it's the best solution because the Orderless attribute gets re-set seemingly at random.
     
    Last edited: May 27, 2009
Know someone interested in this topic? Share a link to this question via email, Google+, Twitter, or Facebook

Have something to add?