|
1 |
| -## Put comments here that give an overall description of what your |
2 |
| -## functions do |
| 1 | +## makeCacheMatrix function creates a matrix wrapper that combines matrix data |
| 2 | +## with its inverse |
| 3 | +## cacheSolve computes the inverse of a matrix created with makeCacheMatrix, |
| 4 | +## if it is called more than once with the same object, the cached value of |
| 5 | +## matrix inverse is returned |
| 6 | +## |
| 7 | +## Example |
| 8 | +## cm <- makeCacheMatrix(matrix(c(1, 0, -4, -2, 2, 5, 1, -8, 9), 3, 3)) |
| 9 | +## cacheSolve(cm) |
| 10 | +## second call will return a cached value |
| 11 | +## cacheSolve(cm) |
3 | 12 |
|
4 |
| -## Write a short comment describing this function |
| 13 | +## returns a matrix wrapper object allowing to cache its inverse |
5 | 14 |
|
6 | 15 | makeCacheMatrix <- function(x = matrix()) {
|
7 |
| - |
| 16 | + xinv <- NULL |
| 17 | + getinv <- function() xinv |
| 18 | + setinv <- function(inverse) xinv <<- inverse |
| 19 | + get <- function() x |
| 20 | + set <- function(y) { |
| 21 | + x <<- y |
| 22 | + xinv <<- NULL |
| 23 | + } |
| 24 | + list(get = get, set = set, |
| 25 | + get.inverse = getinv, set.inverse = setinv) |
8 | 26 | }
|
9 | 27 |
|
10 | 28 |
|
11 |
| -## Write a short comment describing this function |
| 29 | +## Cached version of solve for cache matrix objects, |
| 30 | +## it returns the inverse of x if solve function succeeds |
12 | 31 |
|
13 | 32 | cacheSolve <- function(x, ...) {
|
14 |
| - ## Return a matrix that is the inverse of 'x' |
| 33 | + ## Return a matrix that is the inverse of 'x' |
| 34 | + xinv <- x$get.inverse() |
| 35 | + if (is.null(xinv)) { |
| 36 | + tryCatch({ |
| 37 | + xinv <- solve(x$get(), ...) |
| 38 | + x$set.inverse(xinv) |
| 39 | + }, error = function(e) stop("Non inversible matrix")) |
| 40 | + } else { |
| 41 | + message("Getting cached matrix inverse") |
| 42 | + } |
| 43 | + xinv |
15 | 44 | }
|
0 commit comments