Dismiss Notice
Join Physics Forums Today!
The friendliest, high quality science and math community on the planet! Everyone who loves science is here!

Mathematica : Easy? Function that returns and increases counter.

Tags:
  1. Feb 15, 2014 #1

    Hepth

    User Avatar
    Gold Member

    I have a statement that looks like :

    vD.vD.vD.vD

    Where vD is noncommutative (but that doesnt really matter)

    I want to replace it so that each vD becomes v[a].D[a]

    But I would like it so the "a" is not repeating. So I need somehow a function that each time it is run returns it with an increased index : v[a[1]].D[a[1]]
    So that
    vD.vD.vD /.{vD :> FXN}
    results in
    v[a[1]].D[a[1]].v[a[2]].D[a[2]].v[a[3]].D[a[3]]


    Does anyone know how to do this?
     
  2. jcsd
  3. Feb 15, 2014 #2
    Would something like Product[v[a[j]].d[a[j]], {j, 1, 3}] work for you?
     
  4. Feb 15, 2014 #3

    Hepth

    User Avatar
    Gold Member

    No, i need a replacement rule.

    Lets say my chain is like:

    chain = A.vD.B.C.vD.vD.E.F

    i want something so I can say:

    chain/.{vD:> XXXXX}

    where the result would be

    A.v[a[1]].D[a[1]].B.C.v[a[2]].D[a[2]].v[a[3]].D[a[3]].E.F

    and then if I did it again, it would be

    A.v[a[4]].D[a[4]].B.C.v[a[5]].D[a[5]].v[a[6]].D[a[6]].E.F


    So there is some hidden counter I can set "acount = 0"

    Then when I make a replacement rule, it not only replaces it, but increments the counter:

    chain/.{vD:> v[a[acount]].D[a[acount]];acount++;}

    but I cant force a command like a++ to run in a replacement rule, and if I make it a Do statement, I dont know how to return what I want....


    Ah, I just tried this and it worked!!
    cnt=0;
    chain /. {vD :> v[a[cnt]].DD[a[cnt++]]}

    So obviously simple Im an idiot :)
     
  5. Feb 15, 2014 #4
    Aha. Yeah, I wondered if the product solution was too simple to suggest but then I remembered that I once spent an hour perfecting a recursive algorithm in java to format a text string before someone reminded me that I could just have used a string replace function.

    Nice solution, by the way.
     
Know someone interested in this topic? Share this thread via Reddit, Google+, Twitter, or Facebook




Similar Discussions: Mathematica : Easy? Function that returns and increases counter.
  1. Mathematica functions (Replies: 1)

Loading...