From 24105850c877f04060c79a75d90d780bd211a388 Mon Sep 17 00:00:00 2001 From: Goharimahabadi <116256107+Goharimahabadi@users.noreply.github.com> Date: Thu, 12 Sep 2024 17:06:11 +0200 Subject: [PATCH] Update cachematrix.R --- cachematrix.R | 56 ++++++++++++++++++++++++++++++++++++++------------- 1 file changed, 42 insertions(+), 14 deletions(-) diff --git a/cachematrix.R b/cachematrix.R index 7fd007ea6f0..6d70e34205f 100644 --- a/cachematrix.R +++ b/cachematrix.R @@ -7,17 +7,28 @@ https://www.coursera.org/learn/r-programming/discussions/weeks/3/threads/ePlO1eM R session: -> # Matrices for testing the R functions -> # makeCacheMatrix and cacheSolve -> # in the Coursera R Programming Course -> # -> # First, -> # If you haven't read Leonard Greski's invaluable -> # [TIPS] Demystifying makeVector() Post -> # be sure to do so. -> # -> # A simple matrix m1 with a simple matrix inverse n1 -> # Define +>makeCacheMatrix <- function(x = matrix()) { + inv <- NULL + + # Set the matrix + set <- function(y) { + x <<- y + inv <<- NULL + } + + # Get the matrix + get <- function() x + + # Set the inverse + setInverse <- function(inverse) inv <<- inverse + + # Get the inverse + getInverse <- function() inv + + # Return a list of methods + list(set = set, get = get, setInverse = setInverse, getInverse = getInverse) +} + > m1 <- matrix(c(1/2, -1/4, -1, 3/4), nrow = 2, ncol = 2) > m1 [,1] [,2] @@ -85,8 +96,25 @@ R session: > # > myMatrix_object <- makeCacheMatrix(m1) > -> # and then -> # cacheSolve(myMatrix_object) +> cacheSolve <- function(x, ...) { + # Check if the inverse is already calculated + inv <- x$getInverse() + + if (!is.null(inv)) { + message("getting cached data") + return(inv) + } + + # Calculate the inverse + mat <- x$get() + inv <- solve(mat, ...) + + # Store the inverse in the cache + x$setInverse(inv) + + inv +} + > > # should return exactly the matrix n1 > cacheSolve(myMatrix_object) @@ -117,4 +145,4 @@ getting cached data [,1] [,2] [1,] 3 7 [2,] 1 5 -> \ No newline at end of file +>