determinant_laplace <- function(M, k = 1) {
n <- nrow(M)
det_value <- 0
sign <- 1
for (j in 1:n) {
sub_matrix <- M[-k, -j]
sub_det <- determinant_laplace(sub_matrix, k = 1)
det_value <- det_value + sign * M[k, j] * sub_det
sign <- -sign
}
return(det_value)
}
# Example usage
B = matrix(1:9,nrow=3,ncol=3)
B
determinant_laplace(B)
det(B)
This is what I have so far. When I run it I get a error," Error in 1:n : argument of length 0". I ran it with debugger on and found that n is NULL but I don't know why or how to fix it. Any help would be appreciated.
Update
As pointed out by @Onyambu in the comment, you should be aware that
k=1can be hard coded within your function (rather than taken as an input argument), since you always start the expansion from the 1st row of matrices during the recursion. That means, we, indeed, are able to simplify the function further.Below is an example with further simplification
You are using recursion to compute the matrix determinant and I think you missed two things in your code (see the first two comments and the code below)
and a simple test we can try