|
1 |
| -## Put comments here that give an overall description of what your |
2 |
| -## functions do |
| 1 | +## Put comments here that give an overall description of what your functions do |
3 | 2 |
|
4 |
| -## Write a short comment describing this function |
5 |
| - |
6 |
| -makeCacheMatrix <- function(x = matrix()) { |
7 | 3 |
|
| 4 | +## defines setters and getters for Matrix and its inverse, it takes as a parameter |
| 5 | +## a matrix we assume that all the provided matrices can be inverted |
| 6 | +makeCacheMatrix <- function(mtx = matrix()) { |
| 7 | + inverseMtx <- NULL |
| 8 | + set <- function(initMtx) { |
| 9 | + mtx <<- initMtx |
| 10 | + inverseMtx <<- NULL |
| 11 | + } |
| 12 | + get <- function() mtx |
| 13 | + setInverse <- function(invMtx) inverseMtx <<- invMtx |
| 14 | + getInverse <- function() inverseMtx |
| 15 | + list(set = set, get = get, setInverse = setInverse, getInverse = getInverse) |
8 | 16 | }
|
9 | 17 |
|
10 | 18 |
|
11 |
| -## Write a short comment describing this function |
12 | 19 |
|
13 |
| -cacheSolve <- function(x, ...) { |
14 |
| - ## Return a matrix that is the inverse of 'x' |
| 20 | +## cacheSolve takes a matrix container that corresponds to the list with getters |
| 21 | +## and setters returned by makeCacheMatrix it checks if the inverse matrix exists |
| 22 | +## if yes it returns it from the cache otherwise it calculates the inverse Matrix |
| 23 | +## using solve function |
| 24 | + |
| 25 | +cacheSolve <- function(mtxContainer, ...) { |
| 26 | + ## first check for the inverse of the matrix is it is not NULL |
| 27 | + inverseMtx <- mtxContainer$getInverse() |
| 28 | + if (!is.null(inverseMtx)) { |
| 29 | + message("getting the cached inverse of the matrix") |
| 30 | + return(inverseMtx) |
| 31 | + } |
| 32 | + ## else calculate the inverse of the matrix |
| 33 | + mtx <- mtxContainer$get() |
| 34 | + inverseMtx <- solve(mtx) |
| 35 | + mtxContainer$setInverse(inverseMtx) |
| 36 | + message("calculating the inverse of the matrix") |
| 37 | + ## Return a matrix that is the inverse of 'mtx' |
| 38 | + inverseMtx |
15 | 39 | }
|
0 commit comments