Skip to content

Commit de854b4

Browse files
committed
Demonstrate function creation
Should also fix travis. @Nowosad and @jannes-m, seem like a good direction of (triangular) travel for c12?
1 parent e5c95b2 commit de854b4

File tree

1 file changed

+22
-7
lines changed

1 file changed

+22
-7
lines changed

12-algorithms.Rmd

Lines changed: 22 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -106,24 +106,41 @@ Where $A$ to $C$ are the triangle's three points and $x$ and $y$ refer to the x
106106
A translation of this formula into R code that works with the data in the matrix representation of a triangle `T1` is:
107107

108108
```{r}
109-
110109
T1[1, 1] * (T1[2, 2] - T1[3, 2]) +
111110
T1[2, 1] * (T1[3, 2] - T1[1, 2]) +
112111
T1[3, 1] * (T1[1, 2] - T1[2, 2]) / 2
113112
```
114113

115114
This code chunk works and outputs the correct result.^[
116-
as can be verified with the formula $A = B * H / 2$ )
115+
as can be verified with the formula for the area of a triangle whose base is horizontal: area equals half of the base width times its height --- $A = B * H / 2$ --- ($10 * 10 / 2$ in this case, as can be seen in Figure \@ref(fig:polycent)).
117116
]
117+
The problem with the previous code chunk is that it is very verbose and difficult to re-run on another object with the same 'triangle matrix' format.
118+
To make the code more generalisable, let's convert the code into a function (something described in \@ref(functions)):
119+
120+
```{r}
121+
t_area = function(x) {
122+
x[1, 1] * (x[2, 2] - x[3, 2]) +
123+
x[2, 1] * (x[3, 2] - x[1, 2]) +
124+
x[3, 1] * (x[1, 2] - x[2, 2]) / 2
125+
}
126+
```
127+
128+
The function `t_area` assumes an input with the same dimensions as the triangle represented in `T1`, with the first three rows and two columns representing coordinates of its edges.
129+
We can verify it works not only on the triangle matrix `T1` as follows:
118130

131+
```{r}
132+
t_area(T1)
133+
```
134+
135+
With this setup tested on the first triangle we can proceed to create many triangles.
119136
The next triangle on the list must have the same origin and can be created as follows:
120137

121138
```{r}
122139
T2 = rbind(O, poly_mat[3:4, ], O)
123140
C2 = (T2[1, ] + T2[2, ] + T2[3, ]) / 3
124141
```
125142

126-
```{r}
143+
```{r polycent, fig.cap="Illustration of centroid calculation."}
127144
plot(poly_mat)
128145
lines(poly_mat)
129146
lines(T1, col = "blue", lwd = 2)
@@ -134,10 +151,8 @@ text(x = C2[1], y = C2[2], "C2", col = "red")
134151

135152
```{r}
136153
i = 2:(nrow(poly_mat) - 1)
137-
Ti = purrr::map(I, ~rbind(O, poly_mat[.:(. + 1), ], O))
138-
A = purrr::map_dbl(Ti, .)
139-
140-
154+
Ti = purrr::map(i, ~rbind(O, poly_mat[.:(. + 1), ], O))
155+
A = purrr::map_dbl(Ti, ~t_area(.))
141156
```
142157

143158

0 commit comments

Comments
 (0)