Skip to content

Commit c32037a

Browse files
committed
Complete assignment 2
1 parent 7f657dd commit c32037a

File tree

1 file changed

+45
-6
lines changed

1 file changed

+45
-6
lines changed

cachematrix.R

Lines changed: 45 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1,15 +1,54 @@
1-
## Put comments here that give an overall description of what your
2-
## functions do
1+
# cachematrix.R
2+
# A suite of functions to cache time-consuming matrix inversion computations
3+
#
4+
# Defines a pseudo "matrix" class which manages the cache,
5+
# and a cacheSolve() function to compute the inverse.
6+
#
7+
# Example:
8+
# m1 <- makeCacheMatrix(matrix(rnorm(16), 4, 4))
9+
# cacheSolve(m1)
10+
#
11+
# Based on https://github.com/rdpeng/ProgrammingAssignment2/blob/master/cachematrix.R
312

4-
## Write a short comment describing this function
513

14+
# Returns a special "matrix" object (list) that can cache its inverse.
615
makeCacheMatrix <- function(x = matrix()) {
16+
cachedInverse <- NULL
717

18+
# Accessors to the underlying matrix data
19+
get <- function () x
20+
set <- function (newMatrix) {
21+
x <<- newMatrix
22+
cachedInverse <<- NULL
23+
}
24+
25+
# Convenient way to call cacheSolve()
26+
getInverse <- function () cacheSolve(obj)
27+
28+
getCachedInverse <- function () cachedInverse
29+
setCachedInverse <- function (inverse) cachedInverse <<- inverse
30+
obj <- list(get = get,
31+
set = set,
32+
getInverse = getInverse,
33+
getCachedInverse = getCachedInverse,
34+
setCachedInverse = setCachedInverse)
835
}
936

1037

11-
## Write a short comment describing this function
38+
# This function computes the inverse of the special "matrix"
39+
# returned by `makeCacheMatrix`.
40+
#
41+
# If the inverse has already been calculated (and the matrix has not changed),
42+
# then the cached result will be returned.
43+
#
44+
# Returns a matrix that is the inverse of 'x'
45+
cacheSolve <- function (x, ...) {
46+
inverse <- x$getCachedInverse()
47+
48+
if (is.null(inverse)) {
49+
inverse <- solve(x$get())
50+
x$setCachedInverse(inverse)
51+
}
1252

13-
cacheSolve <- function(x, ...) {
14-
## Return a matrix that is the inverse of 'x'
53+
inverse
1554
}

0 commit comments

Comments
 (0)