9

I'm new to Mathematica

I'd like to apply Mean pairwise to a list to achieve the following.

badSource = {{0, 0}, {1, 1}, {2, 0}, {3, 1}, {4, 0}};
badInterpolation = {{.5, .5}, {1.5, .5}, {2.5, .5}, {3.5, .5}};
ListLinePlot[{badSource, badInterpolation}, Mesh -> All]

Pairwise Mean

How can this be done in general? Do I need pure functions?

schmijos
  • 265
  • 3
  • 6

1 Answers1

13

You need partitioning, Partition and parameters: 2 for pairs, 1 for unit overhang/offset, and then averaging each pair, using Map, short-notated /@.

Partition[{a, b, c, d}, 2, 1]

{{a, b}, {b, c}, {c, d}}

These will all make the averages:

Mean /@ Partition[N@badSource, 2, 1]

MovingAverage[N@badSource, 2]

ListConvolve[{{.5}, {.5}}, badSource]

ListCorrelate[{{.5}, {.5}}, badSource]

Last two suggested by J. M.

BoLe
  • 5,819
  • 15
  • 33
  • 1
    Instead of the form f /@ Partition[list, ...] use Developer`PartitionMap[f, list, ...]. – rcollyer May 11 '13 at 20:04
  • @rcollyer why? Is it faster? – chris May 13 '13 at 07:58
  • @chris I don't know. Intention wise, it is more apparent, and you can add Developer` to your $ContextPath, so it is almost as simple to type. – rcollyer May 13 '13 at 12:19
  • @rcollyer Great, I didn't know for these additional functions. Help says PartitionMap[f, list, n] is equivalent to Map[f, Partition[list, n]]. Does this, being equivalent, in general means that two calls always return same result yet they don't need to be implemented in the same way? – BoLe May 13 '13 at 17:03
  • I suspect, that Developer`PartitionMap is implemented in terms of Map and Partition, so equivalence (i.e. they always return the same thing) would then be guaranteed. I have not seen the underlying code, so it is merely a suspicion, though a likely one. – rcollyer May 13 '13 at 17:24
  • 3
    @rcollyer I assume that PartitionMap is not implemented in terms of Map and Partition, at least not in their normal syntax and behavior. The latter will do the full partitioning first, then the mapping. PartitionMap does the mapping while the partitioning is done. For example, RandomChoice /@ Partition[Range@1*^6, 100, 1]; will use ~800MB of memory (peak), whereas PartitionMap[RandomChoice, Range@1*^6, 100, 1]; will use ~23MB. – Mr.Wizard May 15 '13 at 11:45
  • @chris the above is for you too. – Mr.Wizard May 15 '13 at 11:45
  • @Mr.Wizard you're right, I wasn't thinking when I wrote that. – rcollyer May 15 '13 at 12:10
  • @Mr.Wizard Experiment is the king. On a side note, I recieved a silver badge for this answer, the lamest sort of. – BoLe May 15 '13 at 12:33