Skip to content

Commit f114e6d

Browse files
committed
Assignment: Caching the Inverse of a Matrix
Matrix inversion is usually a costly computation and there may be some benefit to caching the inverse of a matrix rather than computing it repeatedly. Wrote a pair of functions that cache the inverse of a matrix: - makeCacheMatrix - cacheSolve # Please enter the commit message for your changes. Lines starting # with '#' will be ignored, and an empty message aborts the commit. # On branch master # Your branch is up-to-date with 'origin/master'. # # Changes to be committed: # modified: cachematrix.R #
1 parent 7f657dd commit f114e6d

File tree

1 file changed

+32
-5
lines changed

1 file changed

+32
-5
lines changed

cachematrix.R

Lines changed: 32 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,15 +1,42 @@
1-
## Put comments here that give an overall description of what your
2-
## functions do
1+
## Assignment: Caching the Inverse of a Matrix
2+
## Matrix inversion is usually a costly computation
3+
## and there may be some benefit to caching the inverse of a matrix
4+
## rather than computing it repeatedly.
5+
## Your assignment is to write a pair of functions that cache the inverse of a matrix:
6+
## - makeCacheMatrix
7+
## - cacheSolve
38

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

6-
makeCacheMatrix <- function(x = matrix()) {
10+
## This function creates a special "matrix" object that can cache its inverse.
711

12+
makeCacheMatrix <- function(x = matrix()) {
13+
i <- NULL
14+
set <- function(y) {
15+
x <<- y
16+
i <<- NULL
17+
}
18+
get <- function() x
19+
setinverse <- function(inverse) i <<- inverse
20+
getinverse <- function() i
21+
list(set = set, get = get,
22+
setinverse = setinverse,
23+
getinverse = getinverse)
824
}
925

1026

11-
## Write a short comment describing this function
27+
## This function computes the inverse of the special "matrix" returned by makeCacheMatrix.
28+
## If the inverse has already been calculated (and the matrix has not changed),
29+
## then this function returns the inverse from the cache.
1230

1331
cacheSolve <- function(x, ...) {
1432
## Return a matrix that is the inverse of 'x'
33+
i <- x$getinverse()
34+
if(!is.null(i)) {
35+
message("getting cached data")
36+
return(i)
37+
}
38+
data <- x$get()
39+
i <- solve(data, ...)
40+
x$setinverse(i)
41+
i
1542
}

0 commit comments

Comments
 (0)