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
36 lines (31 loc) · 1.16 KB
/
cachematrix.R
File metadata and controls
36 lines (31 loc) · 1.16 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
## A set of funtionct for caching the inverse of a matrix, for it is a costly computation.
# Need MASS for ginv() function, for solve() function is limited to square numeric or complex matrix only.
library(MASS)
## The makeCacheMatrix function creates a special "matrix" that caches matrix inversion.
makeCacheMatrix <- function(x = matrix()) {
matrixInverse <- NULL
set <- function(y) {
x <<- y
matrixInverse <<- NULL
}
get <- function() x
setInverse <- function(inverse) matrixInverse <<- inverse
getInverse <- function() matrixInverse
list(set = set, get = get,
setInverse = setInverse,
getInverse = getInverse)
}
## The cacheSolve function return a matrix that is the inverse of 'x' from cache
## or calculates it if called for the first time on a specific matrix
cacheSolve <- function(x, ...) {
matrixInverse <- x$getInverse()
if(!is.null(matrixInverse)) {
message("getting cached data")
return(matrixInverse)
}
data <- x$get()
# Using ginv() instead of solve() function, because solve() is limited to square matrix and ginv() is not.
matrixInverse <- ginv(data, ...)
x$setInverse(matrixInverse)
matrixInverse
}