2
$\begingroup$

I am considering the following case. Say that T={p1,p2,p3} represents a triangle. In addition, I want to parameterize the edges of the triangle T. What I currently do is:

edgesT = {
   t T[[1]] + (1 - t) T[[2]],
   t T[[2]] + (1 - t) T[[3]],
   t T[[3]] + (1 - t) T[[1]]};

This seems to be very naive, and I would like to learn how can I improve this. One, somehow obvious, way would be to have a cyclic list. Thus the question's title.

Is there a (smart) way to treat a list as cyclic?

Obviously, T[[i]] = pi for i={1,2,3}. It could be useful, for example in the example above, to enter T[[4]] and expect to have p1 as an output. Is there some way to do it?

If not, how can I improve the definition above?

$\endgroup$
8
$\begingroup$

There is a nice function RotateLeft:

edgesT[t_] := t T + (1 - t) RotateLeft[T];
$\endgroup$
5
$\begingroup$

Getting the cyclic index is just a case of using Mod for instance: T[[Mod[n, 3, 1]]]. But as for making this simpler, I would suggest using a SubValue definition to get a cyclicList header which acts as though it was a cyclic list. This is accomplished through:

 cyclicList /: cyclicList[v__][[n_Integer]] := {v}[[Mod[n, Length@{v}, 1]]]

 T = cyclicList[p1, p2, p3];
 edgesT = Table[t T[[n]] + (1 - t) T[[n + 1]], {n, 3}]
$\endgroup$
3
$\begingroup$

A nice way to treat a list as cyclic is Partition:

tri = {a, b, c};

edges = Partition[tri, 2, 1, 1] . {t, 1 - t}
(*  {b (1 - t) + a t, c (1 - t) + b t, a (1 - t) + c t} *)

tri2 = {{a1, a2}, {b1, b2}, {c1, c2}};
Transpose@Partition[tri2, 2, 1, 1].{t, 1 - t}

(* {{a2 (1 - t) + a1 t, b2 (1 - t) + b1 t, c2 (1 - t) + c1 t},
    {b2 (1 - t) + b1 t, c2 (1 - t) + c1 t, a2 (1 - t) + a1 t}} *)
$\endgroup$
  • $\begingroup$ This somehow doesn't work for me if I set a={a1,a2}, b={b1,b2} and `c={c1,c2} (such that they'll represent vertices). $\endgroup$ – Dror Oct 18 '13 at 13:13
1
$\begingroup$
 Inner[t # + (1 - t) #2 &, T, RotateLeft@T, List]
$\endgroup$
1
$\begingroup$

Mathematica already provides a build-in API to generate this kind of correlation.

ListCorrelate[{t, 1 - t}, {p1, p2, p3}, 2]

{p1 (1 - t) + p3 t, p2 (1 - t) + p1 t, p3 (1 - t) + p2 t}

$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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