3
$\begingroup$

I have a list of 2D points which I partition every time the distance between consecutive list elements is bigger than a certain threshold. In a second step I select all the lists that start within a radius of 1 from the origin.

Any ideas to improve my current code?

Generate some test data:

data = Flatten[
   Table[Table[
     Table[a + s RotationMatrix[b].{0, 1}, {s, 0, 10, 0.1}], {b, 
      RandomReal[2 Pi, 5]}], {a, {{0, .1}, {1, 2}, {0.4, 0.2}, {1, 
       1}, {-2, 1}}}], 2];
ListPlot@Partition[data, 101]

enter image description here

Partition the data:

sepL = Most[0.2 > Norm[#1 - #2] & @@@ Transpose[{data, RotateLeft@data}]];
parts = Partition[Flatten@{1, 1 + Accumulate[Length@# & /@ Split[sepL]]}, 2];
res = Select[data[[#1 ;; #2]] & @@@ parts, Norm[#[[1]]] < 1 &];
ListPlot@res

enter image description here

$\endgroup$

2 Answers 2

2
$\begingroup$
SeedRandom[42];
data = Flatten[Table[Table[Table[a + s RotationMatrix[b].{0, 1}, {s, 0, 10, 0.1}],
     {b, RandomReal[2 Pi, 5]}], {a, {{0, .1}, {1, 2}, {0.4, 0.2}, {1, 1}, {-2, 1}}}], 2];

res2 = Split[data, Norm[#1 - #2] < .2 &]; 
res == res2 (* res = SplitBy[data, Norm[f@# - #] < .2 &]; -- from belisarius' post *)
(* True *)

data2 = Pick[res2, Norm@First@# < 1. & /@ res2];
(* or data2 = Pick[res2, Unitize[Norm@First@res2 - 1.], 0]; *)
ListPlot[data2]

enter image description here

$\endgroup$
2
$\begingroup$

You could do something like a flip-flop:

ClearAll[f, h];
Module[{i = True},
       h[_] := {};
       f[x_] := (h[i = ! i] = x;
                 If[# == {}, x, #] &@h[! i])
 ]
res = SplitBy[data, Norm[f@# - #] < .2 &];
ListPlot@Select[res, Norm[#[[1]]] < 1 &]

Mathematica graphics

$\endgroup$
2
  • $\begingroup$ @belisarius It gets slower and slower as you update it, please stop ;) $\endgroup$
    – paw
    Commented Oct 6, 2014 at 18:39
  • $\begingroup$ @paw Oh,sorry. I was trying to make the code easier to understand and disregarding the performance issues. You can always find the older versions at the revision history of course $\endgroup$ Commented Oct 6, 2014 at 18:42

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.