|
1 |
| -## Put comments here that give an overall description of what your |
2 |
| -## functions do |
| 1 | +## Functions for computing cached matrix inversions |
3 | 2 |
|
4 |
| -## Write a short comment describing this function |
| 3 | +## makeCacheMatrix creates a cached matrix object for storing cached inversion results |
| 4 | +## Parameter x is the initial matrix stored in the cache |
5 | 5 |
|
6 | 6 | makeCacheMatrix <- function(x = matrix()) {
|
7 |
| - |
| 7 | + inv <- NULL |
| 8 | + |
| 9 | + # Sets the matrix whose inverse is cached |
| 10 | + set <- function(y) { |
| 11 | + x <<- y |
| 12 | + inv <<- NULL |
| 13 | + } |
| 14 | + |
| 15 | + # Gets the matrix whose inverse is cached |
| 16 | + get <- function() { |
| 17 | + x |
| 18 | + } |
| 19 | + |
| 20 | + # Sets the inverse value of the matrix |
| 21 | + setinverse <- function(i) { |
| 22 | + inv <<- i |
| 23 | + } |
| 24 | + |
| 25 | + # Gets the inverse value of the matrix |
| 26 | + getinverse <- function() { |
| 27 | + inv |
| 28 | + } |
| 29 | + |
| 30 | + # Return the object as a vector of functions |
| 31 | + list(set=set, get=get, setinverse=setinverse, getinverse=getinverse) |
8 | 32 | }
|
9 | 33 |
|
10 | 34 |
|
11 |
| -## Write a short comment describing this function |
| 35 | +## cacheSolve computes the inverse of the given matrix x, using cached results when available |
| 36 | +## Parameter x must be a cached matrix object created using makeCacheMatrix() |
12 | 37 |
|
13 | 38 | cacheSolve <- function(x, ...) {
|
14 |
| - ## Return a matrix that is the inverse of 'x' |
| 39 | + # Check if solution is cached |
| 40 | + inv <- x$getinverse() |
| 41 | + if (!is.null(inv)) { |
| 42 | + # Yes, it was cached, return it |
| 43 | + return(inv) |
| 44 | + } |
| 45 | + |
| 46 | + # No, solution not yet cached, compute it now and cache it |
| 47 | + data <- x$get() |
| 48 | + inv <- solve(data, ...) |
| 49 | + x$setinverse(inv) |
| 50 | + |
| 51 | + # Return the inverse matrix |
| 52 | + inv |
15 | 53 | }
|
0 commit comments