|
1 |
| -## Put comments here that give an overall description of what your |
2 |
| -## functions do |
3 |
| - |
4 |
| -## Write a short comment describing this function |
5 |
| - |
| 1 | +## 'makeCacheMatrix' creates a special "vector", which is really a list containing functions to |
| 2 | +## set the value of the matrix |
| 3 | +## get the value of the matrix |
| 4 | +## set the value of the matrix inverse |
| 5 | +## get the value of the matrix inverse |
6 | 6 | makeCacheMatrix <- function(x = matrix()) {
|
7 |
| - |
| 7 | + inverse <- NULL |
| 8 | + # set the matrix value |
| 9 | + set <- function(matrixToStore) { |
| 10 | + x <<- matrixToStore |
| 11 | + inverse <<- NULL |
| 12 | + } |
| 13 | + # get the matrix value |
| 14 | + get <- function() x |
| 15 | + # set the calculated matrix inverse |
| 16 | + setinverse <- function(inv) inverse <<- inv |
| 17 | + # get calculated matrix inverse |
| 18 | + getinverse <- function() inverse |
| 19 | + list(set = set, get = get, |
| 20 | + setinverse = setinverse, |
| 21 | + getinverse = getinverse) |
8 | 22 | }
|
9 | 23 |
|
10 | 24 |
|
11 |
| -## Write a short comment describing this function |
12 |
| - |
13 |
| -cacheSolve <- function(x, ...) { |
14 |
| - ## Return a matrix that is the inverse of 'x' |
| 25 | +## 'cacheSolve' function returns a matrix that is the inverse of 'x' |
| 26 | +## if the matrix inverse is not found (first call) it calculates the inverse |
| 27 | +## for the given matrix 'x', stores the result in cache and returns it. |
| 28 | +## Every subsequent call will return already calculated inverse stored in cache |
| 29 | +cacheSolve <- function(x = matrix(), ...) { |
| 30 | + ## check if the inverse is available and return it if it already exists |
| 31 | + matrixInverse <- x$getinverse() |
| 32 | + if(!is.null(matrixInverse)) { |
| 33 | + message("getting cached data") |
| 34 | + return(matrixInverse) |
| 35 | + } |
| 36 | + ## if the inverse was not found in cache calculate it, store for later calls and return |
| 37 | + data <- x$get() |
| 38 | + matrixInverse <- solve(data, ...) |
| 39 | + x$setinverse(matrixInverse) |
| 40 | + matrixInverse |
15 | 41 | }
|
0 commit comments