I suggest that we use Mathematica's list manipulation capabilities to eliminate the For
loops. Here's a subdivide
function:
subdivide[verts_List, n_] := Flatten[Most[
Transpose[
Subdivide[Sequence @@ #, n] &/@ #]] &/@
Transpose/@Partition[Append[verts, First@verts], 2, 1], 1]
Example: each side of a square divided into two parts
verts = CirclePoints[Sqrt[2], 4];
n = 2;
subdivisions = subdivide[verts, n];
Graphics[{EdgeForm[Black], FaceForm[None], Polygon[verts],
Red, PointSize[Scaled[.025]], Point[subdivisions]}, ImageSize -> 240]
Example: each side of a random, five-sided polygon divided into four parts
SeedRandom[2];
verts = RandomPolygon[5][[1]];
n = 4;
subdivisions = subdivide[verts, n];
Graphics[{EdgeForm[Black], FaceForm[None], Polygon[verts],
Red, PointSize[Scaled[.025]], Point[subdivisions]}, ImageSize -> 240]
Details of the subdivide function
The first step is to start with the vertices' coordinate pairs, {{x1, y1}, ... {xn, yn}}
, then rearrange pairs into the x
and y
pair coordinates for the start and end points of each side. For example:
verts = {{x1, y1}, {x2, y2}, {x3, y3}};
Transpose/@Partition[Append[verts,First@verts], 2, 1]
{{{x1, x2}, {y1, y2}}, {{x2, x3}, {y2, y3}}, {{x3, x1},{y3, y1}}}
Next, use Subdivide
to find the n
subdivisions of each side, and Transpose
back into {x, y}
pairs. Because the last point of each line is the first point of the following line, use Most
to remove the duplicates. Flatten
gives the resulting list of points for subdivisions
.
]
somewhere to finish off your firstFor
$\endgroup$subdivide
to return the value insubdivisions
? If so then do you want that;
at the end of that? Next, you might include one more line of code at the end, maybe something likesubdivide[{1,2,5},4]
or whatever would be good example input to your function. Next, you might try restarting MMA and running your code again. MMA has a cache and keeps track of previous assignments. Sometimes recursion errors are the result of a variable or function still being in cache. At the moment I'm getting an odd error about missing)
that I haven't figured out. $\endgroup$subdivisons = {};
has a typo. Second, remove the semicolon after the finalsubdivisions;
$\endgroup$