3

Very simple question but I am an absolute beginner, so apologies if this has already been answered.

I need to pick sequential elements of a list, excluding t=1 and t=T, and use them in a function. For ht the list element in position t,

h:={h1,h2,h3,...hT}
hnew=f[t_]:=h[[t-1]]-h[[t+1]]

Then I want to update the existing value of $h_t$ by $h_{new}$, where $h_{new} = h_{t-1}-h_{t+1}$ and repeat until T-1 (second to last element).

Please note that I heed the definition h:={} because at the end of the process the updated vector will replace the original one (this is part of a bigger loop).

I have tried ReplacePart and a Do loop but I could not get them to work.

Again, I apologise for the format and if this question has already been asked.

Titus
  • 1,370
  • 9
  • 18

2 Answers2

5

This is to me a typical Mathematica solution.

f[{a_, b_}] := b
f[{b_, c_}] := b
f[{a_, b_, c_}] := a - c
Developer`PartitionMap[f, list, 3, 1, {-2, 2}, {}]

PartitionMap is a combination of Partition and Map (/@).

Partition is used to create sublists:

Partition[Range[5], 3, 1, {-2, 2}, {}]
(* Out: {{1, 2}, {1, 2, 3}, {2, 3, 4}, {3, 4, 5}, {4, 5}} *)

And mapping f onto this list gives us

f /@ {{1, 2}, {1, 2, 3}, {2, 3, 4}, {3, 4, 5}, {4, 5}}
(* Out: {f[{1, 2}], f[{1, 2, 3}], f[{2, 3, 4}], f[{3, 4, 5}], f[{4, 5}]} *)

So as you can see f now has all of the right data that it needs to compute the element at the position that it occupies in the list. We need to create a function that extracts this information and uses it appropriately. And this is the function that we've already seen:

f[{a_, b_}] := b
f[{b_, c_}] := b
f[{a_, b_, c_}] := a - c
C. E.
  • 70,533
  • 6
  • 140
  • 264
  • Many thanks! That solved my problem and now I only have to deal with updating the list. Next time I will use a copyable format too. Any suggestions on how to update the list are more than welcome. – Titus Jul 10 '15 at 15:01
  • @titus What do you mean by "update the list"? list = Developer`PartitionMap[f,list,...]? – C. E. Jul 10 '15 at 16:57
2

Using the undocumented 6-argument form of Partition where the sixth argument can be function:

foo = Subtract @@ ({##}[[{1, -1}]]) &;
Partition[Array[Subscript[h, #] &, {6}], 3, 1, None, {}, foo] // TeXForm

$\left\{h_1 - h_3, h_2 - h_4, h_3 - h_5, h_4 - h_6\right\}$

Further examples:

Partition[Range[5], 3, 1, None, {}, foo]

{-2, -2, -2}

Partition[RandomSample @ Range[5], 3, 1, None, {}, foo]

{-3, -1, 4}

kglr
  • 394,356
  • 18
  • 477
  • 896