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

Mathematica: Splitting a function into a list of terms

  1. Oct 13, 2011 #1

    I need to split an expression into a list of terms, i.e. an expression like:

    Can you help? Thanks in advance.
  2. jcsd
  3. Oct 13, 2011 #2
    Maybe it's not too slick, but I came up with this:

    myString = "a+b-c-d";
    If[StringTake[myString, 1] != "-", myString = "+" <> myString,];
    list = StringSplit[myString, {"+" -> "1", "-" -> "-1"}];
    listout = Range[Length
    • /2];
      For[i = 1, i <= Length
      • /2, i++,
        listout[] = ToExpression[list[[2 i - 1]]]*ToExpression[list[[2 i]]]];

        which gives {a,b,-c,-d}.
  4. Oct 13, 2011 #3
    String methods are probably not the best for this problem.

    If you look at the FullForm[a+b-c-d] you see that it's
    Plus[a, b, Times[-1, c], Times[-1, d]]
    So all you need to do is make the Plus become a List.
    This can be done using Apply, which has the short hand of @@.
    So, the following should return True
    List@@(a+b-c-d) == {a,b,-c,-d}

    See http://stackoverflow.com/q/7697614/421225 for more discussion and different options.
Share this great discussion with others via Reddit, Google+, Twitter, or Facebook