diff --git a/cachematrix.R b/cachematrix.R index a50be65aa44..3b1ca99e67a 100644 --- a/cachematrix.R +++ b/cachematrix.R @@ -13,3 +13,43 @@ makeCacheMatrix <- function(x = matrix()) { cacheSolve <- function(x, ...) { ## Return a matrix that is the inverse of 'x' } +makeCacheMatrix <- function(x = matrix()) { + inv <- NULL + + set <- function(y) { + x <<- y + inv <<- NULL + } + + get <- function() x + + setinverse <- function(inverse) inv <<- inverse + + getinverse <- function() inv + + list(set = set, get = get, + setinverse = setinverse, + getinverse = getinverse) +} +cacheSolve <- function(x, ...) { + inv <- x$getinverse() + + if (!is.null(inv)) { + message("getting cached data") + return(inv) + } + + mat <- x$get() + inv <- solve(mat, ...) + x$setinverse(inv) + + inv +} + +my_matrix <- makeCacheMatrix(matrix(c(1, 2, 3, 4), nrow = 2)) +cacheSolve(my_matrix) + +cacheSolve(my_matrix) +git add cachematrix.R +git commit -m "Completed cachematrix assignment" +git push origin main