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
66 lines (50 loc) · 1.66 KB
/
cachematrix.R
File metadata and controls
66 lines (50 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
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
## Put comments here that give an overall description of what your
## functions do
##makeCacheMatrix creates a special matrix with list of the following
##function
##1. Set the matrix
##2. Get the matrix
##3. Set the Inverse of the matrix
##4. Get the Inverse of the matrix
makeCacheMatrix <- function(x = matrix()) {
#m is the cached result of solve operation
m <- NULL
#set and get the matrix respectively
#matrix
set <- function(y) {
x <<- y
m <<- NULL
}
get <- function() x
#setinv and getinv are to set/get the inverse of the matrix
# or any other result which caller wants to store respectively
#Assign the calculated solution
setinv <- function(solution) m <<- solution
#Return the calculated solution
getinv <- function() m
list(set = set, get = get,
setinv = setinv,
getinv = getinv)
}
##cacheSolve find the inverse of special matrix created by makeCacheMatrix
##If the inverse is already calculated, it gives the precalculated inverse.
##Else, it computes the inverse and stores it in special matrix.
cacheSolve <- function(x, ...) {
## Return a matrix that is the inverse of 'x'
m <- x$getinv()
#It founds the precomputed inverse
if(!is.null(m)) {
message("getting cached matrix inverse")
return(m)
}
#Else, compute the inverse
data <- x$get()
m <- solve(data, ...)
x$setinv(m)
m
}
###Example: How to test or use?
### c<-rbind(c(1,-1),c(-1,1))
### y<-makeCacheMatrix(c)
### cacheSolve(y)
### On the next call to cacheSolve(y), it will give the matrix inverse from cache.