|
1 |
| -## Put comments here that give an overall description of what your |
2 |
| -## functions do |
| 1 | +## These functions provide a way to cache the result of a possibly slow calculation, |
| 2 | +## such as the inverse of a matrix. |
| 3 | +## The matrix to be inverted must be inputted into the makeCacheMatrix. |
| 4 | +## Then the object returned by makeCacheMatrix must be passed to the cacheSolve |
| 5 | +## function which will return the inverted matrix (either cached or computed) |
3 | 6 |
|
4 |
| -## Write a short comment describing this function |
| 7 | +## This function creates a special "matrix" object that can cache its inverse. |
| 8 | +## Actually it's only a list of function to operate with the matrix value and |
| 9 | +## store its inverse |
5 | 10 |
|
6 | 11 | makeCacheMatrix <- function(x = matrix()) {
|
7 |
| - |
| 12 | + |
| 13 | + inverse <- NULL |
| 14 | + set <- function(m) { |
| 15 | + x <<- m |
| 16 | + inverse <<- NULL |
| 17 | + } |
| 18 | + get <- function() x |
| 19 | + setinverse <- function(inv) inverse <<- inv |
| 20 | + getinverse <- function() inverse |
| 21 | + list(set = set, get = get, |
| 22 | + setinverse = setinverse, |
| 23 | + getinverse = getinverse) |
8 | 24 | }
|
9 | 25 |
|
10 | 26 |
|
11 |
| -## Write a short comment describing this function |
| 27 | +## This function computes the inverse of the special "matrix" returned by |
| 28 | +## makeCacheMatrix above. |
| 29 | +## If the inverse has already been calculated (and the matrix has not changed), |
| 30 | +## then the cachesolve retrieves the inverse from the cache printing a log message. |
12 | 31 |
|
13 | 32 | cacheSolve <- function(x, ...) {
|
14 |
| - ## Return a matrix that is the inverse of 'x' |
| 33 | + |
| 34 | + inverse <- x$getinverse() |
| 35 | + if(!is.null(inverse)) { |
| 36 | + message("getting cached data") |
| 37 | + return(inverse) |
| 38 | + } |
| 39 | + data <- x$get() |
| 40 | + inverse <- solve(data, ...) |
| 41 | + x$setinverse(inverse) |
| 42 | + inverse |
15 | 43 | }
|
0 commit comments