Mathematica: Splitting a function into a list of terms

Click For Summary
SUMMARY

The discussion focuses on splitting a mathematical expression in Mathematica into a list of terms. The user initially attempts to achieve this using string manipulation but is advised to utilize the built-in functionality of Mathematica. The recommended solution involves using the Apply function with the List operator, which effectively transforms the expression into the desired format. The final expression List@@(a+b-c-d) successfully outputs {a, b, -c, -d}.

PREREQUISITES
  • Familiarity with Mathematica syntax and functions
  • Understanding of mathematical expressions and their representation in programming
  • Knowledge of string manipulation techniques in Mathematica
  • Experience with the Apply function and its shorthand notation
NEXT STEPS
  • Explore the Apply function in Mathematica for advanced data manipulation
  • Learn about expression manipulation techniques in Mathematica
  • Investigate the FullForm function to understand expression structures
  • Review additional string manipulation methods in Mathematica for complex scenarios
USEFUL FOR

Mathematica users, mathematicians, and programmers looking to manipulate mathematical expressions efficiently.

TenFold
Messages
2
Reaction score
0
Hi,

I need to split an expression into a list of terms, i.e. an expression like:
a+b-c-d+...
into:
{a,b,-c,-d,...}.

Can you help? Thanks in advance.
 
Physics news on Phys.org
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]]]];
      listout

      which gives {a,b,-c,-d}.
 
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.
 

Similar threads

  • · Replies 6 ·
Replies
6
Views
4K
  • · Replies 3 ·
Replies
3
Views
4K
  • · Replies 4 ·
Replies
4
Views
4K
  • · Replies 1 ·
Replies
1
Views
2K
  • · Replies 13 ·
Replies
13
Views
3K
  • · Replies 4 ·
Replies
4
Views
3K
  • · Replies 1 ·
Replies
1
Views
3K
  • · Replies 4 ·
Replies
4
Views
2K
  • · Replies 9 ·
Replies
9
Views
3K
  • · Replies 2 ·
Replies
2
Views
3K