| New Reply |
Basic Mathematica pattern matching |
Share Thread | Thread Tools |
| May16-12, 11:54 AM | #1 |
|
|
Basic Mathematica pattern matching
So I want to be able to count the number of neighbour pairs of opposite sign in a list of 1's and -1's (eg. 1 for {1,1,1,-1,-1} and 3 for {1,-1,1,-1,-1}), but I can't work out the pattern matching syntax in Mathematica even after reading the documentation. I was thinking to use the Count function. Anybody able to help, please?
|
| May16-12, 02:04 PM | #2 |
|
|
Like so many things in Mathematica, I don't know how you would ever stumble onto this on your own.
This will tell you the positions where the sign flip happens. In[1]:= ReplaceList[{1,1,1,-1,-1}, {pre___, 1,-1,___}|{pre___,-1,1,___} :>Length[{pre}]+1] Out[1]= {3} In[2]:= ReplaceList[{1,-1,1,-1,-1}, {pre___,1,-1,___}|{pre___,-1,1,___} :>Length[{pre}]+1] Out[2]= {1,3,2} This trick courtesy http://mathematica.stackexchange.com...ence-in-a-list among other places And if you wrap a Length[] around those it will tell you how many sign flips. In[3]:= Length[ReplaceList[{1,-1,1,-1,-1}, {pre___,1,-1,___}|{pre___,-1,1,___} :>Length[{pre}]+1]] Out[3]= 3 When would you think that the way to find how many of something you have is to begin by destroying your data? MatchQ doesn't work, Position doesn't work, Count doesn't work, not as far as I've ever been able to find. |
| May16-12, 08:06 PM | #3 |
|
|
How unintuitive! Thanks for that Bill, I wouldn't have figured it out on my own.
|
| New Reply |
| Thread Tools | |
Similar Threads for: Basic Mathematica pattern matching
|
||||
| Thread | Forum | Replies | ||
| Mathematica Pattern matching and replace repeated | Math & Science Software | 2 | ||
| Mathematica,Pattern matching and ReplaceRepeated. | Engineering, Comp Sci, & Technology Homework | 0 | ||
| Basic Mathematica help | Math & Science Software | 19 | ||
| Mathematica - matching phases | Math & Science Software | 0 | ||
| Basic help with Mathematica 5.2, please? | Math & Science Software | 1 | ||