# How to generate a triangular grid from a list of points?

I am newbie with mathematica and the other day I saw a function that generates points from an original one defined as:

h[x_, y_, 0] := Prepend[Table[{Cos[2 Pi k/6] + x, Sin[2 Pi k/6] + y}, {k,6}], {0, 0}]

h[x_, y_, n_] :=DeleteDuplicates[Flatten[Table[{Cos[2 Pi k/6] + #1, Sin[2 Pi k/6] + #2}, {k, 6}] & @@@h[x, y, n - 1], 1]]


So I started from this function and tried to create a triangle lattice with a new function definied as:

L[x_, y_, n_] :=Show@Graphics@While[j < Length[h[x, y, n] + 1],
For[i = 1, i < Length[h[x, y, n] + 1] , i++ ,
If[EuclideanDistance[h[x, y, n][[j]], h[x, y, n][[i]]] == 1,
Line[{h[x, y, n][[j]], h[x, y, n][[i]]}],
Point[{h[x, y, n][[j]], h[x, y, n][[i]]}]]]; j++]


But it doesn't work... I wanted to connect all the dots that were seperated by a distance of 1 and plot a graphic with them. It seems that i am not using for as it should properly be.

• I've edited your question to include a link to what you saw the other day. In the future, make sure to do this so that you can give questions and answerers their proper credit! In addition, once you have enough rep (which I think you do), make sure to upvote questions and/or answers that you found useful (which includes the now-linked ones, I assume, since you asked a question about it!). Commented May 15, 2019 at 23:33

Your code wasn't far off, though the other answers may be more elegant.

This works:

L2[x_, y_, n_] := Module[{pts},
pts = h[x, y, n];
Show[Graphics[{
Point[pts],
Table[
If[EuclideanDistance[pts[[i]], pts[[j]]] == 1,
Line[{pts[[i]], pts[[j]]}]], {i, Length[pts]}, {j, Length[pts]}]
}]]]

L2[0, 0, 2]


Try this:

R = DelaunayMesh[h[0, 0, 2]]


You may grab the edge indices with

MeshCells[R, 1]


You can use NearestNeighborGraph as follows:

Line[{##}] & @@@ EdgeList@NearestNeighborGraph[h[0, 0, 1]] // Graphics


Another way to use NearestNeighborGraph:

NearestNeighborGraph[h[0, 0, 1], VertexCoordinates -> h[0, 0, 1]]


Alternatively, you can use RelationGraph:

RelationGraph[.1 < EuclideanDistance@## <= 1 &, h[0, 0, 1], VertexCoordinates -> h[0, 0, 1]]


same picture

To remove the vertices and to get a Graphics object you can use:

Show @ NearestNeighborGraph[h[0, 0, 1], VertexCoordinates -> h[0, 0, 1],
VertexShapeFunction -> None]


• Thank you for your help! I didn't know there was a function, I appreciate your help. Commented May 16, 2019 at 17:48