Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Commit cfbe74a

Browse files
committed
Submit the first change of the 2nd Assignment
1 parent 7f657dd commit cfbe74a

File tree

1 file changed

+32
-8
lines changed

1 file changed

+32
-8
lines changed

cachematrix.R

Lines changed: 32 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -1,15 +1,39 @@
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
32

4-
## Write a short comment describing this function
5-
6-
makeCacheMatrix <- function(x = matrix()) {
73

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)
816
}
917

1018

11-
## Write a short comment describing this function
1219

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
1539
}

0 commit comments

Comments
 (0)