From 8624dd99af0cf066748b0ef52eaddf248a0a1d7b Mon Sep 17 00:00:00 2001 From: Nirmit3 Date: Fri, 30 May 2025 22:21:31 +0530 Subject: [PATCH 1/2] Update cachematrix.R --- cachematrix.R | 32 ++++++++++++++++++++++---------- 1 file changed, 22 insertions(+), 10 deletions(-) diff --git a/cachematrix.R b/cachematrix.R index a50be65aa44..5b43f08d60b 100644 --- a/cachematrix.R +++ b/cachematrix.R @@ -1,15 +1,27 @@ -## Put comments here that give an overall description of what your -## functions do - -## Write a short comment describing this function - +## This function creates a special "matrix" object that can cache its inverse. makeCacheMatrix <- function(x = matrix()) { - + inv <- NULL # initialize inverse as NULL + set <- function(y) { + x <<- y # assign new matrix value + inv <<- NULL # reset inverse cache + } + get <- function() x + setinverse <- function(inverse) inv <<- inverse + getinverse <- function() inv + list(set = set, get = get, + setinverse = setinverse, + getinverse = getinverse) } - -## Write a short comment describing this function - +## This function computes the inverse of the special "matrix" returned by makeCacheMatrix above. cacheSolve <- function(x, ...) { - ## Return a matrix that is the inverse of 'x' + inv <- x$getinverse() + if(!is.null(inv)) { + message("getting cached data") + return(inv) # return cached inverse + } + data <- x$get() + inv <- solve(data, ...) # compute inverse + x$setinverse(inv) # cache the inverse + inv } From 6e581708dafc723d31a397f14191052a46ee8ad8 Mon Sep 17 00:00:00 2001 From: Nirmit3 Date: Fri, 30 May 2025 22:40:06 +0530 Subject: [PATCH 2/2] Create .Rhistory --- .Rhistory | 26 ++++++++++++++++++++++++++ 1 file changed, 26 insertions(+) create mode 100644 .Rhistory diff --git a/.Rhistory b/.Rhistory new file mode 100644 index 00000000000..054ee17affe --- /dev/null +++ b/.Rhistory @@ -0,0 +1,26 @@ +## This function creates a special "matrix" object that can cache its inverse. +makeCacheMatrix <- function(x = matrix()) { +inv <- NULL # initialize inverse as NULL +set <- function(y) { +x <<- y # assign new matrix value +inv <<- NULL # reset inverse cache +} +get <- function() x +setinverse <- function(inverse) inv <<- inverse +getinverse <- function() inv +list(set = set, get = get, +setinverse = setinverse, +getinverse = getinverse) +} +## This function computes the inverse of the special "matrix" returned by makeCacheMatrix above. +cacheSolve <- function(x, ...) { +inv <- x$getinverse() +if(!is.null(inv)) { +message("getting cached data") +return(inv) # return cached inverse +} +data <- x$get() +inv <- solve(data, ...) # compute inverse +x$setinverse(inv) # cache the inverse +inv +}