|
1 |
| -## Put comments here that give an overall description of what your |
2 |
| -## functions do |
3 |
| - |
4 |
| -## Write a short comment describing this function |
| 1 | +## As part of R programming assignment 2 we're asked to |
| 2 | +## write pair of functions that cache inverse of a matrix. |
5 | 3 |
|
| 4 | +## makeCacheMatrix function will create a special "matrix" |
| 5 | +## object that can cache its inverse. |
6 | 6 | makeCacheMatrix <- function(x = matrix()) {
|
7 |
| - |
| 7 | + ## initialize |
| 8 | + m <- NULL |
| 9 | + |
| 10 | + ## set matrix function |
| 11 | + set <- function (matrix) { |
| 12 | + x <<- matrix |
| 13 | + m <<- NULL |
| 14 | + } |
| 15 | + |
| 16 | + ## get matrix function |
| 17 | + get <- function() { |
| 18 | + x |
| 19 | + } |
| 20 | + |
| 21 | + ## set inverse matrix function |
| 22 | + setInverse <- function(inverse) { |
| 23 | + m <<- inverse |
| 24 | + } |
| 25 | + |
| 26 | + ## get inverse matrix function |
| 27 | + getInverse <- function () { |
| 28 | + m |
| 29 | + } |
| 30 | + |
| 31 | + ## return list of functions |
| 32 | + list (set = set, |
| 33 | + get = get, |
| 34 | + setInverse = setInverse |
| 35 | + getInverse = getInverse) |
8 | 36 | }
|
9 | 37 |
|
10 | 38 |
|
11 |
| -## Write a short comment describing this function |
12 |
| - |
| 39 | +## cacheSolve function will compute the inverse of the special "matrix" |
| 40 | +## returned by makeCacheMatrix above. If the inverse has already been |
| 41 | +## calculated (and the matrix has not changed), then the CacheSolve |
| 42 | +## function should retrieve the inverse from the cache. |
13 | 43 | cacheSolve <- function(x, ...) {
|
14 | 44 | ## Return a matrix that is the inverse of 'x'
|
| 45 | + m < x$getInverse() |
| 46 | + |
| 47 | + ## Retrieve inverse from cache |
| 48 | + if (!is.null(m)) { |
| 49 | + message("Inverse already calculated. get cached data") |
| 50 | + return(m) |
| 51 | + } |
| 52 | + |
| 53 | + |
| 54 | + ## get matrix |
| 55 | + data <- x$get() |
| 56 | + |
| 57 | + ## calculate inverse matrix |
| 58 | + m <- solve(data) %*% data |
| 59 | + |
| 60 | + ## set inverse matrix |
| 61 | + x$setInverse(m) |
| 62 | + |
| 63 | + ## return matrix |
| 64 | + m |
15 | 65 | }
|
0 commit comments