0
$\begingroup$

In the example code which follows I define a two variable conditional function h[_i, _v], one variable denotes the integer index i, and the other is an N-dimensional vector v (I denote dimension 'N' by 'Num'). I am interested in how to do a folding list type evaluation (or any other efficient method) of this two variable function h[_i,_v], where we carry over the evaluated vector value v to the next index i.e. For Num = 3 I am looking for $$h[3,h[2,h[1,v]]].$$ The code which defines this function h is as follows:

Num = 3; p;

M0 = {{Sqrt[1 - p], 0}, {0, Sqrt[1 - p]}}; M1 = {{Sqrt[p], 
   0}, {0, -Sqrt[p]}}; Id = {{1, 0}, {0, 1}};

A1 = Table[Id, {i, Num - 1}]; PrependTo[A1, M0]; Pe = Permutations[A1];
MM0 = Table[KroneckerProduct @@ Pe[[i]], {i, Length[A1]}];

A2 = Table[Id, {i, Num - 1}]; PrependTo[A2, M1];
Pe = Permutations[A2];
MM1 = Table[KroneckerProduct @@ Pe[[i]], {i, Length[A2]}];

e1 = RandomVariate[UniformDistribution[{0, 1}], Num]
e2 = RandomVariate[UniformDistribution[{0, 1}], Num]

f[i_, v_] := MM1[[i]] . v/Norm[MM1[[i]] . v]
g[i_, v_] := MM0[[i]] . v/Norm[MM0[[i]] . v]
h[i_, v_] := If[e1[[i]] < e2[[i]], f[i, v], g[i, v]]

The available documentation seems to specifically address the single variable FoldList case. Thanks for any assistance.

$\endgroup$

1 Answer 1

2
$\begingroup$

You can use Fold and switch i and v in your definition of h ...

h[v_, i_] := ...

Fold[h, v, Range[3]]

(* h[h[h[v, 1], 2], 3] *)

... or switch the order directly in Fold.

h[i_, v_] := ...

Fold[h[#2, #1] &, v, Range[3]]

(* h[3, h[2, h[1, v]]] *)
$\endgroup$
4
  • $\begingroup$ Many thanks for the response. Just one query, how would you adapt the code to repeat this folding process for a given number of rounds. Hence for two rounds I am interested in $$[3,h[2,h[1,h[3,h[2,h[1,v]]]]]].$$ You can advise if I should post as separate question. $\endgroup$
    – John Doe
    Commented Oct 12, 2021 at 20:48
  • 1
    $\begingroup$ Use Nest: Nest[Fold[h[#2, #1] &, #, Range[3]] &, v, 2]. $\endgroup$
    – Domen
    Commented Oct 12, 2021 at 20:56
  • $\begingroup$ This might be a trivial question (new to Mathematica), but how exactly are you using #2 and #1 to switch arguments? Is this something that you can only do this way within the Fold function? Or is this a general trick for argument switch? $\endgroup$
    – John Doe
    Commented Oct 13, 2021 at 8:25
  • 1
    $\begingroup$ The syntax above uses pure functions, and the hash symbols represent Slot. It is a much more general and broader concept, and it is not something special for Fold. $\endgroup$
    – Domen
    Commented Oct 13, 2021 at 13:40

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.