Skip to content

Commit 894cec5

Browse files
committed
Implemented makeCacheMatrix and cacheSolve.
1 parent 7f657dd commit 894cec5

File tree

1 file changed

+50
-5
lines changed

1 file changed

+50
-5
lines changed

cachematrix.R

Lines changed: 50 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,15 +1,60 @@
1-
## Put comments here that give an overall description of what your
2-
## functions do
1+
## cachematrix.R
2+
##
3+
## Computing the inverse of a matrix can be a time consuming
4+
## process. If the matrix does not change, its inverse does
5+
## not change, so it is a reasonable strategy to store the
6+
## inverse when it is first needed, and retrieve the stored
7+
## value if it is needed again, which avoids the need to
8+
## recompute it.
39

4-
## Write a short comment describing this function
10+
## makeCacheMatrix:
11+
## Create a list of functions which can be used to store and
12+
## manipulate a square invertible matrix and its inverse.
13+
##
14+
## If the matrix is altered (with the "set" function), any
15+
## previously cached value is likely to be invalid, so the
16+
## cache is reset.
17+
##
18+
## Returns this list of functions:
19+
## set: set the value of the matrix
20+
## get: get the value of the matrix
21+
## setinverse: set the cached value of the inverse
22+
## getinverse: get the cached value of the inverse
523

624
makeCacheMatrix <- function(x = matrix()) {
7-
25+
inverse <- NULL
26+
set <- function(y) {
27+
x <<- y
28+
inverse <<- NULL
29+
}
30+
get <- function() x
31+
setinverse <- function(inv) inverse <<- inv
32+
getinverse <- function() inverse
33+
list (set = set,
34+
get = get,
35+
setinverse = setinverse,
36+
getinverse = getinverse)
837
}
938

1039

11-
## Write a short comment describing this function
40+
## cacheSolve:
41+
## Return a matrix which is the inverse of the matrix created by
42+
## the "makeCacheMatrix" function.
43+
##
44+
## The first time this function is run for a matrix, it
45+
## computes the inverse and stores it, and on subsequent runs it
46+
## will return this stored value, avoiding the need to compute it
47+
## more than once.
1248

1349
cacheSolve <- function(x, ...) {
1450
## Return a matrix that is the inverse of 'x'
51+
inv <- x$getinverse()
52+
if(!is.null(inv)) {
53+
message("getting cached data")
54+
return(inv)
55+
}
56+
data <- x$get()
57+
inv <- solve(data)
58+
x$setinverse(inv)
59+
inv
1560
}

0 commit comments

Comments
 (0)