Take the 2-minute tour ×
Mathematica Stack Exchange is a question and answer site for users of Mathematica. It's 100% free, no registration required.

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?

share|improve this question
    

5 Answers 5

up vote 8 down vote accepted

There is a nice function RotateLeft:

edgesT[t_] := t T + (1 - t) RotateLeft[T];
share|improve this answer

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}]
share|improve this answer

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}} *)
share|improve this answer
    
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). –  Dror Oct 18 '13 at 13:13
 Inner[t # + (1 - t) #2 &, T, RotateLeft@T, List]
share|improve this answer

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}

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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