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

Skip to content

Commit 07a50f6

Browse files
committed
ProgrammingAssignment2
1 parent 7f657dd commit 07a50f6

File tree

1 file changed

+29
-6
lines changed

1 file changed

+29
-6
lines changed

cachematrix.R

Lines changed: 29 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1,15 +1,38 @@
1-
## Put comments here that give an overall description of what your
2-
## functions do
1+
## These two functions together calculate the inverse of a square matrix
2+
## The result is put in a cache, so that the next time that the inverse of the same matrix
3+
## is needed it is retrieved from the cache, instead of doing the costly calculation again
34

4-
## Write a short comment describing this function
5+
## Make an object that stores the original matrix and its inverse in another environment (cache)
56

67
makeCacheMatrix <- function(x = matrix()) {
7-
8+
mi <- NULL
9+
set <- function(y) {
10+
x <<- y
11+
mi <<- NULL
12+
}
13+
get <- function() x
14+
setinverse <- function(inverse) mi <<- inverse
15+
getinverse <- function() mi
16+
list(set = set, get = get,
17+
setinverse = setinverse,
18+
getinverse = getinverse)
819
}
920

1021

11-
## Write a short comment describing this function
22+
## This function tries to get the inverse of the the matrix stored in the cache of the object x
23+
## and return it
24+
## If the inverse is not found in the cache, then the inverse is calculated and the value is
25+
## stored in the cache of the object x and then returned
1226

1327
cacheSolve <- function(x, ...) {
14-
## Return a matrix that is the inverse of 'x'
28+
mi <- x$getinverse()
29+
if(!is.null(mi)) {
30+
message("getting cached data")
31+
return(mi)
32+
}
33+
data <- x$get()
34+
mi <- solve(data, ...)
35+
x$setinverse(mi)
36+
## Return a matrix that is the inverse of 'x'
37+
mi
1538
}

0 commit comments

Comments
 (0)