'write a function that accepts a square matrix as arguments and returns the determinant of the matrix by means of Laplace expansion along row

Complete the code chunk in the template to write a function that accepts a square matrix (of any size, including a scalar) M and an integer k (default = 1) as arguments and returns the determinant of the matrix by means of Laplace expansion along row k.

You may not use the built-in det() function within your function. You may need to check whether the supplied value of k is reasonable/possible and return an error message if not.

If you are not able to program this Laplace expansion, you may use the det() function in further questions to prevent a further loss of marks.


my_det <- function(M, k = 1) {
  
  if(length(M) == 1) {
    
    return(M)
    
  }
  
  else if(k > dim(M)[1]) {
    
    return("ERROR: k is larger than the dimension of x")
    
  }
  
  else if(dim(M)[1] == 2) {
    
    return( M[1,1] * M[2,2] - M[1,2] * M[2,1] )


Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source