Compute the unsigned surface area of triangles defined by vertex coordinates. Works with both 2D (xy) and 3D (xyz) input. For 2D input, z coordinates are assumed to be zero.

triangle_surface_area(x)

Arguments

x

A matrix with 2 or 3 columns (x, y) or (x, y, z). Each set of 3 consecutive rows defines one triangle.

Value

A numeric vector of surface areas, one per triangle.

Details

The area is calculated using the cross product method: Area = 0.5 * ||(v1 - v0) x (v2 - v0)||

For 2D input, this reduces to the absolute value of the shoelace formula.

Examples

# 2D triangle (unit right triangle)
tri_2d <- matrix(c(0, 0,
                   1, 0,
                   0, 1), ncol = 2, byrow = TRUE)
triangle_surface_area(tri_2d)  # 0.5
#> [1] 0.5

# 3D triangle
tri_3d <- matrix(c(0, 0, 0,
                   1, 0, 0,
                   0, 1, 1), ncol = 3, byrow = TRUE)
triangle_surface_area(tri_3d)
#> [1] 0.7071068