|
1 |
| -## Put comments here that give an overall description of what your |
2 |
| -## functions do |
| 1 | +## These functions are used to cache the inverse of a matrix. |
| 2 | +## The purpose is to avoid the same computations again and again |
| 3 | +## of matrix inversions by caching the result. |
3 | 4 |
|
4 |
| -## Write a short comment describing this function |
| 5 | +## `makeCacheMatrix` function creates a special "matrix" object that can cache its inverse. |
| 6 | +## It returns a list of functions to: |
| 7 | +## - set the value of the matrix |
| 8 | +## - get the value of the matrix |
| 9 | +## - set the value of the inverse |
| 10 | +## - get the value of the inverse |
5 | 11 |
|
| 12 | +# Function `makeCacheMatrix` |
6 | 13 | makeCacheMatrix <- function(x = matrix()) {
|
7 |
| - |
| 14 | + inv <- NULL |
| 15 | + set <- function(y) { |
| 16 | + x <<- y |
| 17 | + inv <<- NULL |
| 18 | + } |
| 19 | + get <- function() x |
| 20 | + setInverse <- function(inverse) inv <<- inverse |
| 21 | + getInverse <- function() inv |
| 22 | + list(set = set, get = get, setInverse = setInverse, getInverse = getInverse) |
8 | 23 | }
|
9 | 24 |
|
10 | 25 |
|
11 |
| -## Write a short comment describing this function |
| 26 | +## This function computes the inverse of the special "matrix" object created |
| 27 | +## by `makeCacheMatrix`. If the inverse has already been calculated and the matrix |
| 28 | +## has not changed, it retrieves the cached inverse to save computation time. |
| 29 | +## Otherwise, it calculates the inverse and stores it in the cache. |
12 | 30 |
|
| 31 | +# Function `cacheSolve` |
13 | 32 | cacheSolve <- function(x, ...) {
|
14 |
| - ## Return a matrix that is the inverse of 'x' |
| 33 | + inv <- x$getInverse() |
| 34 | + if(!is.null(inv)) { |
| 35 | + message("getting cached data") |
| 36 | + return(inv) |
| 37 | + } |
| 38 | + data <- x$get() |
| 39 | + inv <- solve(data, ...) |
| 40 | + x$setInverse(inv) |
| 41 | + inv |
15 | 42 | }
|
0 commit comments