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
44 lines (38 loc) · 1.6 KB
/
Copy pathcachematrix.R
File metadata and controls
44 lines (38 loc) · 1.6 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
## This is the function that can calculate and cache the inverse of a matrix x.
## The following function is useful to speed up the time-comsuming repeating computations of a large data set.
## Usage: testmatrix <-makeCacheMatrix(inputmatrix)
## cacheSolve(testmatrix) ## first time it calculate the inverse matrix
## cacheSolve(testmatrix) ## second time it returns the cached matrix
## The makeCacheMatrix function creates a special matrix containing a function to
## 1. set the value of the matrix
## 2. get the value of the matrix
## 3. set the value of the inverse
## 4. get the value of the inverse
makeCacheMatrix <- function(x = matrix()) {
invm <- NULL
set <- function(y) {
x <<- y
invm <<- NULL
}
get <- function() x ## return the input matrix x
setinverse <- function(inverse) invm <<- inverse
getinverse <- function() invm
list(set = set, get = get, setinverse = setinverse, getinverse = getinverse)
}
## The cacheSolve function first check if the inverse value has already been calulated,
## if so, it returns the inverse matrix from the cache and skip the computation.
## If not, it calculates the inverse of the matrix, and sets the matrix in the cache.
cacheSolve <- function(x, ...) {
##
invm <- x$getinverse()
## If invm exist, return the cached inverse matrix
if (!is.null(invm)){
message("getting cached data")
return(invm)
}
## Otherwise calculate the inverse matrix
data <- x$get()
m <- solve(data, ...)
x$setinverse(m) ## save the value in the cache by setinverse function
m
}