3
$\begingroup$

I want to create a fractal tree, using translation and rotation. Code below is working for one level, but when I try loop, it is not giving output. Code is given below:

 threshold = 4; L = 100; While[ L > threshold, line = Line[{{0, 0}, {0, -L}}]; Graphics[ {line, Scale[#, 2/3, {0, 0}] & /@ (Rotate[ Translate[line, {0, L}], # Degree, {0, 0}] & /@ {-30, 30})}] L = L*0.67; ]; 
$\endgroup$
1
  • 1
    $\begingroup$ Related: 154213. $\endgroup$ Commented Sep 2, 2018 at 12:09

3 Answers 3

6
$\begingroup$
ClearAll[next]; next[{{x1_, y1_}, {x2_, y2_}}] = ( {{x1, y1}, {x2, y2}} // TranslationTransform[{x2 - x1, y2 - y1}] // RotationTransform[# Pi/6, {x2, y2}] // ScalingTransform[2/3 {1, 1}, {x2, y2}] ) & /@ {-1, 1}; list = NestList[Join @@ next /@ # &, N@{{{0, 0}, {0, 1}}}, 5]; Graphics[Line /@ list] 

enter image description here

$\endgroup$
2
  • $\begingroup$ Nice, Thank you so very much @chyang. $\endgroup$ Commented Sep 2, 2018 at 14:33
  • $\begingroup$ @BiSarfraz You are welcome. $\endgroup$ Commented Sep 3, 2018 at 6:25
8
$\begingroup$

I am not only new in Mathematica, but also new in Maths. I need a very simple approach

(This answer attempts to be a "reference answer" with relevant links.)

This has been discussed extensively in MSE and Mathematica blogs and demonstrations.

$\endgroup$
2
  • $\begingroup$ Thank you so much. $\endgroup$ Commented Sep 2, 2018 at 14:25
  • $\begingroup$ @BiSarfraz You are welcome, good luck! $\endgroup$ Commented Sep 2, 2018 at 14:28
3
$\begingroup$

The main issue with your code is that it's lacking a way to combine the different levels of the tree. Graphics are not automatically printed, unless they are the final result of a computation.

The following code should get you started:

tree[L_, th_] /; L > th := With[ {line = Line[{{0, 0}, {0, -L}}]}, { line, Scale[#, 2/3, {0, 0}] & /@ (Rotate[Translate[tree[0.67 L, th], {0, L}], # Degree, {0, 0}] & /@ {-30, 30})} ] tree[__] := {} tree[100, 10] // Graphics 

Mathematica graphics

The key ingredients are:

  • Recursion of the tree function to combine the different parts. The termination condition is implemented using Condition (/;)
  • Rotate,Scale,Transform can be arbitrarily nested, allowing for a clean specification of the nested levels

As you can see, the result is not correct yet (the lines are too short), but you should be able to easily fix that.

$\endgroup$
2
  • $\begingroup$ Thank you so much for making things easy. $\endgroup$ Commented Sep 2, 2018 at 14:28
  • 1
    $\begingroup$ I have fixed it: line, Scale[#, 2/3, {0, 0}] & /@ (Rotate[Translate[tree[0.67 L, th], {0, 0.67L}], # Degree, {0, 0}] & /@ {-30, 30})} ] $\endgroup$ Commented Sep 3, 2018 at 10:12

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.