4
$\begingroup$

So I need to write a function which takes natural integer $n$ and returns graphical representation of a matrix $n \times n$ using ArrayPlot[]. This matrix has to be pixel approximation of equilateral triangle which get better and better as $n$ increases.

I figured out a set of equilateral triangle points which is $$P=\{(x,y) \in \mathbb{R}^2:y<\sqrt{3}x+\frac{a\sqrt{3}}{2},y<-\sqrt{3}x+\frac{a\sqrt{3}}{2},y>0\}$$ where $a$ is side length of this triangle.

f1[x_, a_] := -Sqrt[3]*x + (a*Sqrt[3])/2
f2[x_, a_] := Sqrt[3]*x + (a*Sqrt[3])/2
matrix[n_] := ConstantArray[0, {n, n}]
(...)
drawapprox[n_] := ArrayPlot[matrix[n], Mesh -> True]

So I make zero $n \times n$ matrix and I want to put $1$ if a point belongs to $P$ but I don't know how to put together points from the plane to this 0-1 matrix to make it works. After that I just want to use ArrayPlot[] function to draw new 0-1 matrix which represents triangle.

How do I make up the missing (...) part?

$\endgroup$
6
$\begingroup$

Update: An alternative method using SparseArray:

ClearAll[f1, f2, sa, aplot2]
f1[x_, a_] := -Sqrt[3]*x + (a*Sqrt[3])/2
f2[x_, a_] := Sqrt[3]*x + (a*Sqrt[3])/2

sa[a_] := SparseArray[{i_, j_} /; 
     a - i < f1[j - (a + Boole[OddQ[a]])/2, a] && 
     a - i < f2[j - (a + Boole[OddQ[a]])/2, a] -> 1, {a, a}]
aplot2[a_] := ArrayPlot[sa[a], Mesh -> All]

Row[aplot2 /@ Range[3, 21, 2]]

enter image description here

Original answer:

ClearAll[f1, f2, aplot]
f1[x_, a_] := -Sqrt[3]*x + (a*Sqrt[3])/2
f2[x_, a_] := Sqrt[3]*x + (a*Sqrt[3])/2
aplot[a_] := ArrayPlot[Boole @ MapIndexed[
       a - #2[[1]] < f1[#2[[2]] - (a + Boole[OddQ[a]])/2, a] && 
       a - #2[[1]] < f2[#2[[2]] - (a + Boole[OddQ[a]])/2, a] &, 
     ConstantArray[0, {a, a}], {2}], Mesh -> All];

Row[Show[aplot@#, Graphics[{FaceForm[], EdgeForm[{Thick, Red}], SSSTriangle[#, #, #]}]] & /@
 Range[3, 21, 2]]

enter image description here

With a = 101; and Mesh -> None, we get

a = 1001; 
ap1001 = ArrayPlot[Boole@MapIndexed[
      a - #2[[1]] < f1[#2[[2]] - (a + Boole[OddQ[a]])/2, a] && 
      a - #2[[1]] < f2[#2[[2]] - (a + Boole[OddQ[a]])/2, a] &, 
    ConstantArray[0, {a, a}], {2}], Mesh -> None];

Graphics[{ap1001[[1]], FaceForm[], EdgeForm[{Thick, Red}], 
  SSSTriangle[1001, 1001, 1001]}]

enter image description here

$\endgroup$
  • $\begingroup$ Thank you very much! $\endgroup$ – apoxeiro Mar 10 at 21:54

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.