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

Skip to content

Commit 524bc02

Browse files
committed
functions makeCacheMatrix and cacheSolve for cacheing matrix inversion
1 parent 7f657dd commit 524bc02

File tree

1 file changed

+43
-6
lines changed

1 file changed

+43
-6
lines changed

cachematrix.R

Lines changed: 43 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1,15 +1,52 @@
1-
## Put comments here that give an overall description of what your
2-
## functions do
1+
## The pair of functions makeCacheMatrix() and cacheSolve()
2+
## allow an invertible matrix and its inverse to be cached.
3+
## The inversion function used is solve()
34

4-
## Write a short comment describing this function
5+
## makeCacheMatrix - returns a cacheable invertible matrix.
6+
## x: is an invertible matrix
7+
## set() stores the matrix
8+
## get() retrieves the matrix
9+
## setinverse caches the result of of the inversion function
10+
## getinverse retrieves any cached result
511

612
makeCacheMatrix <- function(x = matrix()) {
7-
13+
inv <- NULL
14+
15+
# store the matrix
16+
set <- function(mx){
17+
x <<- mx
18+
inv <<- NULL
19+
}
20+
get <- function() x
21+
22+
# cache the inverse matrix
23+
setinverse <- function(s) inv <<- s
24+
getinverse <- function() inv
25+
26+
list(set = set,
27+
get = get,
28+
setinverse = setinverse,
29+
getinverse = getinverse)
830
}
931

1032

11-
## Write a short comment describing this function
12-
33+
## cacheSolve - returns the cached inverse of a matrix.
34+
## x: is a cacheable invertible matrix defined by calling
35+
## makeCacheMatrix(M), where M is an invertible matrix
36+
##
37+
1338
cacheSolve <- function(x, ...) {
1439
## Return a matrix that is the inverse of 'x'
40+
# get cached inverse if it exists
41+
inv <- x$getinverse()
42+
if(!is.null(inv)){
43+
message("getting cached data")
44+
return(inv)
45+
}
46+
47+
# create a cached inverse
48+
data <- x$get() # obtain the matrix
49+
inv <- solve(data, ...) # invert the matrix
50+
x$setinverse(inv) # cache the inverse
51+
inv
1552
}

0 commit comments

Comments
 (0)