These functions create a special matrix object that can store a matrix
and cache its inverse, avoiding repeated and costly recalculations
if the matrix hasn't changed.
makeCacheMatrix creates a special "matrix" object, which is actually a list
containing four functions to: set the matrix, get the matrix,
set the inverse, and get the inverse.
makeCacheMatrix <- function(x = matrix()) {
inv <- NULL # This will store the cached inverse (initially empty)
# 1. Function to set a new matrix
set <- function(y) {
x <<- y # Assigns the value to 'x' in the parent environment
inv <<- NULL # Resets the cached inverse to NULL if the matrix changes
}
# 2. Function to get the current matrix
get <- function() x
# 3. Function to save the calculated inverse to the cache
setInverse <- function(inverse) inv <<- inverse
# 4. Function to retrieve the inverse from the cache
getInverse <- function() inv
# Returns a list containing the 4 functions defined above
list(set = set, get = get,
setInverse = setInverse,
getInverse = getInverse)
}
cacheSolve computes the inverse of the special "matrix" returned by makeCacheMatrix.
If the inverse has already been calculated (and the matrix hasn't changed),
it retrieves the result directly from the cache, skipping the computation.
cacheSolve <- function(x, ...) {
## Check if the inverse is already present in the cache
inv <- x$getInverse()
## If it exists (is not NULL), return the message and the cached value
if(!is.null(inv)) {
message("getting cached data")
return(inv)
}
## If it does NOT exist, get the original matrix...
data <- x$get()
## ...calculate the inverse using the solve() function...
inv <- solve(data, ...)
## ...save the calculated inverse to the object's cache...
x$setInverse(inv)
## ...and finally return the inverse matrix
inv
}
These functions create a special matrix object that can store a matrix
and cache its inverse, avoiding repeated and costly recalculations
if the matrix hasn't changed.
makeCacheMatrix creates a special "matrix" object, which is actually a list
containing four functions to: set the matrix, get the matrix,
set the inverse, and get the inverse.
makeCacheMatrix <- function(x = matrix()) {
inv <- NULL # This will store the cached inverse (initially empty)
}
cacheSolve computes the inverse of the special "matrix" returned by makeCacheMatrix.
If the inverse has already been calculated (and the matrix hasn't changed),
it retrieves the result directly from the cache, skipping the computation.
cacheSolve <- function(x, ...) {
## Check if the inverse is already present in the cache
inv <- x$getInverse()
}