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
49 lines (44 loc) · 1.66 KB
/
cachematrix.R
File metadata and controls
49 lines (44 loc) · 1.66 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
#This R script takes a matrix as an input and
#returns the inverse of the matrix. The inverse is cached the first time
#it is evaluated and from then on, it is returned from the cache
#Two functions are used for this purpose - makeCacheMatrix and cachSolve
#The makeCacheMatrix is a formal argument to the cachsolve function
#The makeCacheMatrix takes a matrix as an argument and returns a list
# containing the following 4 functions
#1.A function to set the matrix
#2.A function to get the matrix
#3.A function to set the inverse of the original matrix
#4.A function to get the inverse of the original matrix
# This function uses the operator '<<-' to set the value of the
#inverse. The operator '<<-' looks back in the enclosing environment
#for an environment that contains the variable m and assigns the right
#hand side to the its value.
makeCacheMatrix <- function(x = matrix()) {
m <- NULL
set <- function(y) {
x <<- y
m <<- NULL
}
get <- function() x
setinverse <- function(inv) m <<- inv
getinverse <- function() m
list(set = set, get = get,
setinverse = setinverse,
getinverse = getinverse)
}
#The cachSolve function takes the makeCacheMatrix as an argument.
#This function checks if the inverse exists in cache. If it exists it returns
#the existing inverse else it uses solve() function to calculate the
#inverse and returns the inverse.
cacheSolve <- function(makeCacheMatrix, ...) {
## Return a matrix that is the inverse of 'x'...
m <- makeCacheMatrix$getinverse()
if(!is.null(m)) {
message("getting cached data")
return(m)
}
data <- makeCacheMatrix$get()
m <- solve(data, ...)
makeCacheMatrix$setinverse(m)
m
}