You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Copy file name to clipboardExpand all lines: 12-algorithms.Rmd
+22-7Lines changed: 22 additions & 7 deletions
Original file line number
Diff line number
Diff line change
@@ -106,24 +106,41 @@ Where $A$ to $C$ are the triangle's three points and $x$ and $y$ refer to the x
106
106
A translation of this formula into R code that works with the data in the matrix representation of a triangle `T1` is:
107
107
108
108
```{r}
109
-
110
109
T1[1, 1] * (T1[2, 2] - T1[3, 2]) +
111
110
T1[2, 1] * (T1[3, 2] - T1[1, 2]) +
112
111
T1[3, 1] * (T1[1, 2] - T1[2, 2]) / 2
113
112
```
114
113
115
114
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)).
117
116
]
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:
118
130
131
+
```{r}
132
+
t_area(T1)
133
+
```
134
+
135
+
With this setup tested on the first triangle we can proceed to create many triangles.
119
136
The next triangle on the list must have the same origin and can be created as follows:
120
137
121
138
```{r}
122
139
T2 = rbind(O, poly_mat[3:4, ], O)
123
140
C2 = (T2[1, ] + T2[2, ] + T2[3, ]) / 3
124
141
```
125
142
126
-
```{r}
143
+
```{r polycent, fig.cap="Illustration of centroid calculation."}
127
144
plot(poly_mat)
128
145
lines(poly_mat)
129
146
lines(T1, col = "blue", lwd = 2)
@@ -134,10 +151,8 @@ text(x = C2[1], y = C2[2], "C2", col = "red")
134
151
135
152
```{r}
136
153
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))
0 commit comments