|
1 |
| -## Put comments here that give an overall description of what your |
2 |
| -## functions do |
| 1 | +# Coursera, R Programming(rprog-010), January 2015 |
| 2 | +# Cache the inverse of a matrix |
| 3 | +# Matrix inversion is usually a costly computation and it makes sense |
| 4 | +# to cache the inverse of a matrix rather than compute it repeatedly |
| 5 | +# These two functions calculate and cache the inverse of a matrix. |
3 | 6 |
|
4 |
| -## Write a short comment describing this function |
| 7 | +## Example of usage |
| 8 | +## m <- matrix(c(4, 3, 3, 2), nrow = 2) |
| 9 | +## store the initial matrix in cached matrix object |
| 10 | +## m_cached <- makeCacheMatrix(m) |
| 11 | +## first call will solve the inverse and cache it |
| 12 | +## cacheSolve(m_cashed) |
| 13 | +## second call will return the cached value |
| 14 | +## cacheSolve(m_cashed) |
5 | 15 |
|
| 16 | +# This function creates an interface to access(get) and cache(set) |
| 17 | +# the contents of a matrix and the inverse of original matrix. |
6 | 18 | makeCacheMatrix <- function(x = matrix()) {
|
7 |
| - |
| 19 | + inverse <- NULL |
| 20 | + set <- function(y) { |
| 21 | + x <<- y |
| 22 | + inverse <<- NULL |
| 23 | + } |
| 24 | + get <- function() x |
| 25 | + set_inverse <- function(inv) inverse <<- inv |
| 26 | + get_inverse <- function() inverse |
| 27 | + list(set = set, get = get, |
| 28 | + set_inverse = set_inverse, |
| 29 | + get_inverse = get_inverse) |
8 | 30 | }
|
9 |
| - |
10 |
| - |
11 |
| -## Write a short comment describing this function |
12 |
| - |
| 31 | +# This function computes the inverse of the special "matrix" |
| 32 | +# returned by makeCacheMatrix above. |
13 | 33 | cacheSolve <- function(x, ...) {
|
14 |
| - ## Return a matrix that is the inverse of 'x' |
| 34 | + ## Return a matrix that is the inv_matrix of 'x' |
| 35 | + inverse <- x$get_inverse() |
| 36 | + # check if inverse matrix was already calculated and |
| 37 | + # retrieve the content from the cache. |
| 38 | + if(!is.null(inverse)) { |
| 39 | + message("getting cached data") |
| 40 | + return(inverse) |
| 41 | + } |
| 42 | + # else calculate the inverse matrix |
| 43 | + data <- x$get() |
| 44 | + inverse <- solve(data, ...) |
| 45 | + x$set_inverse(inverse) |
| 46 | + inverse |
15 | 47 | }
|
0 commit comments