diff --git a/HuiYi b/HuiYi new file mode 100644 index 00000000000..3b06ac095f1 --- /dev/null +++ b/HuiYi @@ -0,0 +1,37 @@ +makeCacheMatrix <- function(x = matrix()) { + inv <- NULL # Initialize the inverse as NULL + + # Function to set the matrix and reset cached inverse + set <- function(y) { + x <<- y + inv <<- NULL + } + + # Function to get the matrix + get <- function() x + + # Function to set the cached inverse + setinverse <- function(inverse) inv <<- inverse + + # Function to get the cached inverse + getinverse <- function() inv + + # Return a list of the above functions + list(set = set, get = get, + setinverse = setinverse, + getinverse = getinverse) +} + +cacheSolve <- function(x, ...) { + inv <- x$getinverse() # Check if inverse is already cached + if (!is.null(inv)) { + message("getting cached data") + return(inv) + } + + # If not cached, compute the inverse + mat <- x$get() + inv <- solve(mat, ...) + x$setinverse(inv) # Cache the inverse + inv +}