From e62ca8021f54ef1d2339dbc8701fd87e0f2505f9 Mon Sep 17 00:00:00 2001 From: abhijith-furt Date: Thu, 5 Feb 2026 17:49:01 +0530 Subject: [PATCH] Update cachematrix.R --- cachematrix.R | 56 ++++++++++++++++++++++++++++++++++++++++++--------- 1 file changed, 47 insertions(+), 9 deletions(-) diff --git a/cachematrix.R b/cachematrix.R index a50be65aa44..460dd6b9f76 100644 --- a/cachematrix.R +++ b/cachematrix.R @@ -1,15 +1,53 @@ -## Put comments here that give an overall description of what your -## functions do - -## Write a short comment describing this function +## These functions create a special matrix object that can cache its inverse +## and compute the inverse using caching for efficiency. +## makeCacheMatrix: Creates a special "matrix" object that can cache its inverse makeCacheMatrix <- function(x = matrix()) { - + # Initialize the inverse as NULL + inv <- NULL + + # Set the matrix + set <- function(y) { + x <<- y + inv <<- NULL # Reset inverse when matrix changes + } + + # Get the matrix + get <- function() x + + # Set the inverse + setinverse <- function(inverse) inv <<- inverse + + # Get the inverse + getinverse <- function() inv + + # Return a list of functions + list(set = set, + get = get, + setinverse = setinverse, + getinverse = getinverse) } - -## Write a short comment describing this function - +## cacheSolve: Computes the inverse of the special "matrix" returned by makeCacheMatrix +## If the inverse has already been calculated (and matrix hasn't changed), +## then retrieves inverse from cache cacheSolve <- function(x, ...) { - ## Return a matrix that is the inverse of 'x' + # Get cached inverse + inv <- x$getinverse() + + # If inverse exists in cache, return it + if(!is.null(inv)) { + message("getting cached data") + return(inv) + } + + # Otherwise, compute the inverse + data <- x$get() + inv <- solve(data, ...) + + # Cache the inverse + x$setinverse(inv) + + # Return the inverse + inv }