forked from rdpeng/ProgrammingAssignment2
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcachematrix.R
49 lines (41 loc) · 1.45 KB
/
cachematrix.R
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
## The first function, makeCacheMatrix, creates a special "matrix" object that
## can cache its inverse.
##
## Base assumption for using these functions is that the matrix supplied
## is always invertible.
makeCacheMatrix <- function(x = numeric()) {
## initialize inverse matrix to null
m <- NULL
## set the original matrix and clear the cached inverse
set <- function(y) {
x <<- y
m <<- NULL
}
## get the original matrix
get <- function() x
## set the inverse matrix
setinverse <- function(solve) m <<- solve
## get the inverse matrix
getinverse <- function() m
list(set = set, get = get,
setinverse = setinverse,
getinverse = getinverse)
}
## The cacheSolve function computes the inverse of the "special" matrix returned
## by makeCacheMatrix. If the inverse has already been calculated (and the matrix
## has not changed), then cacheSolve retrieves the inverse from the cache.
cacheSolve <- function(x, ...) {
## If the inverse has already been calculated (and the matrix has not changed),
## then retrieve the inverse from the cache.
m <- x$getinverse()
if(!is.null(m)) {
message("getting cached data")
return(m)
}
## If the inverse has not been calculated then calculate and set the inverse
## in the cache. Return the inverse matrix of 'x'.
data <- x$get()
m <- solve(data, ...)
x$setinverse(m)
m
}