Skip to content

Commit 1a11a00

Browse files
Brian DonaldsonBrian Donaldson
authored andcommitted
Checking in function for cachable matrix
1 parent 7f657dd commit 1a11a00

File tree

1 file changed

+43
-3
lines changed

1 file changed

+43
-3
lines changed

cachematrix.R

Lines changed: 43 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,15 +1,55 @@
11
## Put comments here that give an overall description of what your
22
## functions do
33

4+
2 functions. The first function creates a special matrix object that supports caching its inverse. The second function produces the inverse to the matrix object, using the object's cache if set, and otherwise computing the result.
5+
46
## Write a short comment describing this function
7+
Function returns a matrix object that supports caching its inverse.
58
69
makeCacheMatrix <- function(x = matrix()) {
7-
10+
m <- NULL
11+
set <- function(y) {
12+
x <<- y
13+
m <<- NULL
14+
}
15+
get <- function() x
16+
setsolution <- function(solution) m <<- solution
17+
getsolution <- function() m
18+
list(set = set, get = get,
19+
setsolution = setsolution,
20+
getsolution = getsolution)
821
}
922
10-
1123
## Write a short comment describing this function
24+
Function retrieves the inverse of matrix X, using the cache, and otherwise performs the solve method and then caches the result.
1225
26+
## Return a matrix that is the inverse of 'x'
1327
cacheSolve <- function(x, ...) {
14-
## Return a matrix that is the inverse of 'x'
28+
m <- x$getsolution()
29+
if(!is.null(m)) {
30+
message("getting cached data")
31+
return(m)
32+
}
33+
data <- x$get()
34+
m <- solve(data, ...)
35+
x$setsolution(m)
36+
m
1537
}
38+
39+
## Test
40+
tryme <- makeCacheMatrix(matrix(c(1,2,3,4), nrow=2, ncol=2))
41+
cacheSolve(tryme)
42+
cacheSolve(tryme)
43+
44+
## Test
45+
# > tryme <- makeCacheMatrix(matrix(c(1,2,3,4), nrow=2, ncol=2))
46+
# > cacheSolve(tryme)
47+
# [,1] [,2]
48+
# [1,] -2 1.5
49+
# [2,] 1 -0.5
50+
# > cacheSolve(tryme)
51+
# getting cached data
52+
# [,1] [,2]
53+
# [1,] -2 1.5
54+
# [2,] 1 -0.5
55+
#

0 commit comments

Comments
 (0)