From d29ba637e7dc1beee8e35055f5e81fb3eff311e7 Mon Sep 17 00:00:00 2001 From: ItsKiron <64255294+ItsKiron@users.noreply.github.com> Date: Sat, 30 Aug 2025 12:49:40 +0200 Subject: [PATCH] my submition to the cachematrix.R --- cachematrix.R | 34 ++++++++++++++++++++++++++++++---- 1 file changed, 30 insertions(+), 4 deletions(-) diff --git a/cachematrix.R b/cachematrix.R index a50be65aa44..33188114e36 100644 --- a/cachematrix.R +++ b/cachematrix.R @@ -2,14 +2,40 @@ ## functions do ## Write a short comment describing this function - +# makeCacheMatrix: create a matrix that can store itself and a cached copy of its inverse once its computed makeCacheMatrix <- function(x = matrix()) { - + inv <- NULL # cache for inverse + + set <- function(y) { # replace matrix and reset cache + x <<- y + inv <<- NULL + } + + get <- function() x # return current matrix + + setinverse <- function(inverse) # store computed inverse + inv <<- inverse + + getinverse <- function() inv # return cached inverse (or NULL) + + list(set = set, get = get, + setinverse = setinverse, + getinverse = getinverse) } -## Write a short comment describing this function +## Write a short comment describing this function +# cacheSolve: returns the cached inverse or computes & caches it cacheSolve <- function(x, ...) { - ## Return a matrix that is the inverse of 'x' + inv <- x$getinverse() # try cache first + if (!is.null(inv)) { + message("getting the cached inverse") + return(inv) + } + mat <- x$get() # fetch matrix + inv <- solve(mat, ...) # compute inverse (assumes invertible) + x$setinverse(inv) # cache result + inv # return inverse } +