Skip to content

Commit fb65a91

Browse files
committed
Implemented makeCacheMatrix and cacheSolve functions for Programming Assignment 2
1 parent 7f657dd commit fb65a91

File tree

1 file changed

+74
-6
lines changed

1 file changed

+74
-6
lines changed

cachematrix.R

Lines changed: 74 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1,15 +1,83 @@
1-
## Put comments here that give an overall description of what your
2-
## functions do
1+
## This pair of functions demonstrates the use of R's lexical scoping
2+
## to create a function closure that caches the result of computing
3+
## the inverse of a matrix.
4+
##
5+
## For example, suppose the matrix to be computed is m:
6+
##
7+
## > m <- matrix(c(4, 2, 7, 6), nrow=2, ncol=2)
8+
## > m
9+
## [,1] [,2]
10+
## [1,] 4 7
11+
## [2,] 2 6
12+
##
13+
## We first create the function closure by passing m to
14+
## makeCacheMatrix, storing the result in cache.m:
15+
##
16+
## > cache.m <- makeCacheMatrix(m)
17+
##
18+
## Then we compute the inverse of m by passing cache.m to cacheSolve:
19+
##
20+
## > inv1 <- cacheSolve(cache.m)
21+
## > inv1
22+
## [,1] [,2]
23+
## [1,] 0.6 -0.7
24+
## [2,] -0.2 0.4
25+
##
26+
## If we calculate the inverse a second time, the cached result is
27+
## returned:
28+
##
29+
## > inv2 <- cacheSolve(cache.m)
30+
## getting cached data
31+
## > inv2
32+
## [,1] [,2]
33+
## [1,] 0.6 -0.7
34+
## [2,] -0.2 0.4
35+
##
336

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

6-
makeCacheMatrix <- function(x = matrix()) {
38+
## makeCacheMatrix creates an environment (closure) for caching the
39+
## inverse of a matrix.
40+
##
41+
## The argument x is the matrix to be inverted.
42+
##
43+
## makeCacheMatrix returns a list of functions:
44+
##
45+
## setm - sets the matrix and clears any cached inverse
46+
## getm - gets the matrix
47+
## getinv - gets the inverse
48+
## setinv - sets the inverse
749

50+
makeCacheMatrix <- function(x = matrix()) {
51+
inv <- NULL
52+
setm <- function(y) {
53+
m <<- y
54+
inv <<- NULL
55+
}
56+
getm <- function() m
57+
setinv <- function(inverse) inv <<- inverse
58+
getinv <- function() inv
59+
list(setm = setm, getm = getm, setinv = setinv, getinv = getinv)
860
}
961

1062

11-
## Write a short comment describing this function
63+
## cacheSolve returns the inverse of a matrix.
64+
##
65+
## The argument x is the list of functions returned by
66+
## makeCacheMatrix for the matrix to be inverted.
67+
##
68+
## If the inverse has already been computed, cacheSolve
69+
## returns a cached copy of the inverse.
70+
##
71+
## Note: It is assumed that the matrix is always invertible.
1272

1373
cacheSolve <- function(x, ...) {
14-
## Return a matrix that is the inverse of 'x'
74+
inv <- x$getinv()
75+
if(!is.null(inv)) {
76+
message("getting cached data")
77+
return(inv)
78+
}
79+
mat <- x$getm()
80+
inv <- solve(mat, ...)
81+
x$setinv(inv)
82+
inv
1583
}

0 commit comments

Comments
 (0)