Skip to content

Commit 7657463

Browse files
committed
filled both method stubs "makeCacheMatrix" and "cacheSolve" with code and comments;
verified that caching works via the following timestamping test: now <- Sys.time(); mat <- makeCacheMatrix(h10); cacheSolve(mat); diff <- Sys.time() - now; diff now <- Sys.time(); mat$getinv(); diff <- Sys.time() - now; diff where h10 is the 10x10 hilbert matrix
1 parent 7f657dd commit 7657463

File tree

1 file changed

+41
-4
lines changed

1 file changed

+41
-4
lines changed

cachematrix.R

Lines changed: 41 additions & 4 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+
## These two functions allow for caching the inverse of a matrix, to save
2+
## compuation time for this CPU intensive operation
3+
## For this, two functions are defined:
4+
## - makeCacheMatrix: allows for caching a matrix and its inverse
5+
## - cacheSolve: computing and storing the inverse
36

4-
## Write a short comment describing this function
7+
## allows for caching a matrix and its inverse
58

69
makeCacheMatrix <- function(x = matrix()) {
10+
i <- NULL
11+
## making sure that if a new matrix is set, we store its value
12+
## and reset our inverse (since we haven't calculated it yet)
13+
set <- function(y) {
14+
x <<- y
15+
i <<- NULL
16+
}
717

18+
## return the original base matrix
19+
get <- function() x
20+
21+
## set new value for the inverse
22+
setinv <- function(mat) i <<- mat
23+
24+
## return value of the inverse
25+
getinv <- function() i
26+
list(set = set, get = get, setinv = setinv, getinv = getinv)
827
}
928

1029

11-
## Write a short comment describing this function
30+
## This is the function to which we pass the function (which is really a list)
31+
## "makeCacheMatrix" and compute and store the inverse
1232

1333
cacheSolve <- function(x, ...) {
1434
## Return a matrix that is the inverse of 'x'
35+
i <- x$getinv()
36+
37+
## in case we already know the inverse, we skip recomputing it and return the cached value
38+
if(!is.null(i)) {
39+
message("getting cached inverse")
40+
return(i)
41+
}
42+
43+
## getting our base matrix ...
44+
data <- x$get()
45+
46+
## ... passing it to the R solver (making sure to catch any errors) ...
47+
i <- try(solve(data, ...))
48+
49+
## ... and storing and displaying the result
50+
x$setinv(i)
51+
i
1552
}

0 commit comments

Comments
 (0)