From 6f0337f8069ac4b7bec9448f614a59865eb497a4 Mon Sep 17 00:00:00 2001 From: Prabhat Kumar <104729493+kumar11jr@users.noreply.github.com> Date: Sat, 21 Oct 2023 21:59:19 +0530 Subject: [PATCH] Update cachematrix.R --- cachematrix.R | 59 +++++++++++++++++++++++++++++++++++++++++---------- 1 file changed, 48 insertions(+), 11 deletions(-) diff --git a/cachematrix.R b/cachematrix.R index a50be65aa44..626486cf263 100644 --- a/cachematrix.R +++ b/cachematrix.R @@ -1,15 +1,52 @@ -## Put comments here that give an overall description of what your -## functions do - -## Write a short comment describing this function - -makeCacheMatrix <- function(x = matrix()) { - +makeCacheMatrix <- function(x = numeric()) { + + # holds the cached value or NULL if nothing is cached + # initially nothing is cached so set it to NULL + cache <- NULL + + # store a matrix + setMatrix <- function(newValue) { + x <<- newValue + # since the matrix is assigned a new value, flush the cache + cache <<- NULL + } + + # returns the stored matrix + getMatrix <- function() { + x + } + + # cache the given argument + cacheInverse <- function(solve) { + cache <<- solve + } + + # get the cached value + getInverse <- function() { + cache + } + + # return a list. Each named element of the list is a function + list(setMatrix = setMatrix, getMatrix = getMatrix, cacheInverse = cacheInverse, getInverse = getInverse) } -## Write a short comment describing this function - -cacheSolve <- function(x, ...) { - ## Return a matrix that is the inverse of 'x' +# The following function calculates the inverse of a "special" matrix created with +# makeCacheMatrix +cacheSolve <- function(y, ...) { + # get the cached value + inverse <- y$getInverse() + # if a cached value exists return it + if(!is.null(inverse)) { + message("getting cached data") + return(inverse) + } + # otherwise get the matrix, caclulate the inverse and store it in + # the cache + data <- y$getMatrix() + inverse <- solve(data) + y$cacheInverse(inverse) + + # return the inverse + inverse }