Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a standard function for this?

There is probably built-in function or a better and faster way to do this in Mathematica

func[l_, g_, f_] := g @@ f @@@ Transpose[{Most[l], Rest[l]}]

which can be used to do things like this

l = {a, b, c, d}
func[l, Plus, (#1 - #2)^2 &]

I don't know the proper name for this kind of function. Something in a fold-zip genre.

UPDATE Lot's of solutions. Thanks to everyone.

Using

Partition[l, 2, 1] 

instead of

Transpose[{Most[l], Rest[l]}] 

definitely makes it clearer.

I've tried to run timings on the functions, but I get strange results:

func1[l_, g_, f_] := g @@ f @@@ Transpose[{Most[l], Rest[l]}]
func2[l_, g_, f_] := g @@ f @@@ Partition[l, 2, 1]
func3[l_, g_, f_] := g @@ ListConvolve[{1, 1}, l, {-1, 1}, {}, Times, f]
func4[l_, g_, f_] := g @@ Thread[f[Most@l, Rest@l]]
func5[l_, g_, f_] := g @@ f /@ Partition[l, 2, 1]
func6[l_, g_, f_] := g @@ Thread[f[Most[l], Rest[l]]]
func7[l_, f_, g_] := Inner[f, Sequence @@ Partition[l, Length[l] - 1, 1], g]
func8[l_, g_, f_] := g @@ MapThread[f, Partition[l, Length[l] - 1, 1]]
functions = {func1, func2, func3, func4, func5, func6, func7, func8}

input = Table[ToExpression["x" <> ToString[i]], {i, 1, 1000000}];
inputs = Table[Take[input, i*100000], {i, 1, 10}];

Table[
  If[i == j == 0, "",
  If[j == 0, functions[[i]],
  If[i == 0, Length[inputs[[j]]],
    Timing[functions[[i]][inputs[[j]]]][[1]]]]], 
    {i, 0, Length[functions]}, {j, 0, Length[inputs]}] // Transpose // TableForm
like image 920
Max Avatar asked Dec 30 '25 09:12

Max


1 Answers

If you want something that exactly duplicates the functionality of your func, the only prettyfication I can think of is replacing Transpose[Most[l],Rest[l]] with Partition:

func2[l_,g_,f_]:=g@@f@@@Partition[l,2,1]

If you really want something "built in", you could hack on some ListConvolve for kicks

func3[l_,g_,f_]:=g@@ListConvolve[{1,1},l,{-1,1},{},Times,f]

Checking that all these work:

Through[{func,func2,func3}[l,Plus,(#1-#2)^2&]]
Out[19]= {(a-b)^2+(b-c)^2+(c-d)^2,(a-b)^2+(b-c)^2+(c-d)^2,(a-b)^2+(b-c)^2+(c-d)^2}

Finally, if this is the answer you are looking for, I would suggest computing it by Total[Differences[l]^2]

Out[14]= (-a+b)^2+(-b+c)^2+(-c+d)^2 
like image 123
Janus Avatar answered Jan 02 '26 11:01

Janus



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!