forked from rdpeng/ProgrammingAssignment2
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcachematrix.R
More file actions
60 lines (52 loc) · 1.91 KB
/
cachematrix.R
File metadata and controls
60 lines (52 loc) · 1.91 KB
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
50
51
52
53
54
55
56
57
58
59
60
## Matrix inversion is usually a costly operation and there may be some
## benefit to caching the inverse of a matrix rather than computing it
## every time.
## The following two functions 'makeCacheMatrix' and 'cacheSolve' permit to
## define a special 'matrix' that can cache the inverse matrix in order to
## reduce the time cost of evaluating it repeatedly.
## This function computes the inverse of the special 'matrix' returned by
## the 'makeCacheMatrix' function depicted above.
## If the inverse matrix has already been calculated, this function should
## retrieve the inverse from the cache.
##
## inputs:
## - x: a special 'matrix' created by the 'makeCacheMatrix' function
## - ...: all the extra arguments are passed to the R 'solve' function
##
## outputs:
## the inverse matrix of the input special 'matrix'
makeCacheMatrix <- function(x = matrix()) {
inversematrix <- NULL
set <- function(y) {
x <<- y
inversematrix <<- NULL
}
get <- function() x
setinverse <- function(inverse) inversematrix <<- inverse
getinverse <- function() inversematrix
list(set = set, get = get,
setinverse = setinverse,
getinverse = getinverse)
}
## This function computes the inverse of the special 'matrix' returned by
## the 'makeCacheMatrix' function depicted above.
## If the inverse matrix has already been calculated, then this function should
## retrieve the inverse from the cache.
##
## inputs:
## - x: a special 'matrix' created by the 'makeCacheMatrix' function
## - ...: all the extra arguments are passed to the R solve function
##
## outputs:
## the inverse matrix of the input special 'matrix'
cacheSolve <- function(x, ...) {
inverse <- x$getinverse()
if( !is.null(inverse) ) {
message("getting cached data")
return(inverse)
}
original <- x$get()
inverse <- solve(original, ...)
x$setinverse(inverse)
inverse
}