|
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 | +## function makeCacheMatrix creates an object that is used to store |
| 2 | +## a provided matrix and it's computed inverse |
| 3 | +## it returns a list with matrix getter and setter, along with functions |
| 4 | +## used to store and return computed matrix inverse |
5 | 5 |
|
6 | 6 | makeCacheMatrix <- function(x = matrix()) {
|
7 |
| - |
| 7 | + # variable m is used to |
| 8 | + m <- NULL |
| 9 | + # getter for x matrix |
| 10 | + set <- function(y) { |
| 11 | + x <<- y |
| 12 | + # making sure cache gets NULLified when stored vector is overwritten |
| 13 | + m <<- NULL |
| 14 | + } |
| 15 | + # getter for x matrix |
| 16 | + get <- function() x |
| 17 | + # store matrix inverse |
| 18 | + setinverse <- function(inverse) m <<- inverse |
| 19 | + # get stored matrix inverse |
| 20 | + getinverse <- function() m |
| 21 | + # generating list to be returned |
| 22 | + list(set = set, get = get, |
| 23 | + setinverse = setinverse, |
| 24 | + getinverse = getinverse) |
8 | 25 | }
|
9 | 26 |
|
10 | 27 |
|
11 |
| -## Write a short comment describing this function |
| 28 | +## function cacheSolve is actually solving the equation a %*% x = b for x |
| 29 | +## storing the solution in x object and returning stored solution if available |
12 | 30 |
|
13 | 31 | cacheSolve <- function(x, ...) {
|
14 |
| - ## Return a matrix that is the inverse of 'x' |
| 32 | + # try to get cached matrix inverse from x object |
| 33 | + m <- x$getinverse() |
| 34 | + if(!is.null(m)) { |
| 35 | + # return stored matrix inverse if available |
| 36 | + message("getting cached matrix inverse") |
| 37 | + # stop processing function and return solution from cache in x |
| 38 | + return(m) |
| 39 | + } |
| 40 | + # solve matrix inverse |
| 41 | + data <- x$get() |
| 42 | + m <- solve(data, ...) |
| 43 | + # and store it in x object |
| 44 | + x$setinverse(m) |
| 45 | + m |
15 | 46 | }
|
0 commit comments