Skip to content

Commit 016f288

Browse files
committed
Cache matrix functions implemented.
1 parent 7f657dd commit 016f288

File tree

1 file changed

+47
-9
lines changed

1 file changed

+47
-9
lines changed

cachematrix.R

+47-9
Original file line numberDiff line numberDiff line change
@@ -1,15 +1,53 @@
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-
6-
makeCacheMatrix <- function(x = matrix()) {
1+
# makeCacheMatrix creates a list containing a function to
2+
# 1. set the value of the matrix
3+
# 2. get the value of the matrix
4+
# 3. set the value of inverse of the matrix
5+
# 4. get the value of inverse of the matrix
76

7+
makeCacheMatrix <- function(x = numeric()) {
8+
9+
# holds the cached value or NULL if nothing is cached
10+
# initially nothing is cached so set it to NULL
11+
cache <- NULL
12+
13+
# store a matrix
14+
setMatrix <- function(newValue) {
15+
x <<- newValue
16+
# since the matrix is assigned a new value, flush the cache
17+
cache <<- NULL
18+
}
19+
20+
# returns the stored matrix
21+
getMatrix <- function() {
22+
x
23+
}
24+
25+
# cache the given argument
26+
cacheInverse <- function(solve) {
27+
cache <<- solve
28+
}
29+
30+
# get the cached value
31+
getInverse <- function() {
32+
cache
33+
}
34+
35+
# return a list. Each named element of the list is a function
36+
list(setMatrix = setMatrix, getMatrix = getMatrix, cacheInverse = cacheInverse, getInverse = getInverse)
837
}
938

1039

11-
## Write a short comment describing this function
40+
## Calculate the inverse of the special "matrix" created with the above
41+
## function, reusing cached result if it is available
1242

1343
cacheSolve <- function(x, ...) {
14-
## Return a matrix that is the inverse of 'x'
15-
}
44+
i <- x$getinverse()
45+
if(!is.null(i)) {
46+
message("getting cached data")
47+
return(i)
48+
}
49+
m <- x$get()
50+
i <- solve(m, ...)
51+
x$setinverse(i)
52+
i
53+
}

0 commit comments

Comments
 (0)