I want to write a function to calculate the determinant of a squared matrix be a 2x2
or 3x3
in just one function such that if its users supply just 4 elements it will take it to be a 2x2 and if its users supply 9 elements it will use the 3x3 function. Here are my functions for the 2x2 and the 3x3:
matrix(1:4, ncol=2)
# [,1] [,2]
#[1,] 1 3
#[2,] 2 4
A_22 <- function(x11, x12, x21, x22) {
(x11 * x22) - (x12 * x21)
}
A_22(x11 = 1, x12 = 2, x21 =3, x22 = 4)
#[1] -2
cbind(1,1:3,c(2,0,1))
# [,1] [,2] [,3]
#[1,] 1 1 2
#[2,] 1 2 0
#[3,] 1 3 1
A_33 <- function(x11, x12, x13, x21, x22, x23, x31, x32, x33) {
(x11 * x22 * x33) + (x12 * x23 * x31) + (x13 * x21 * x33) - (x31 * x22 * x13) - (x32 * x23 * x11) - (x33 * x21 * x12)
}
A_33(x11 = 1, x12 = 1, x13 = 2, x21 = 1, x22 = 2, x23 = 0, x31 = 1, x32 = 3, x33 = 1)
#[1] -1
I viewed this solution but it is only applicable to using different methods to solve a problem and not like this question of handling different cases.
What is the elegant way of combining the two different cases of A_22
and A_33
to a parent function?