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
55 lines (43 loc) · 1.62 KB
/
cachematrix.R
File metadata and controls
55 lines (43 loc) · 1.62 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
## Put comments here that give an overall description of what your
## functions do
#makeCacheMatrix: This function creates a special "matrix" object that can cache its inverse.
#cacheSolve: This function computes the inverse of the special "matrix" returned by makeCacheMatrix above. If the inverse has already been calculated (and the matrix has not changed), then the cachesolve should retrieve the inverse from the cache.
#The makecahcematrix function will take advantage of the scoping rules of the R language
makeCacheMatrix <- function(X = matrix()) {
inverse <- NULL
set <- function(Y){
X <<- Y
inverse <<- NULL
}
get <- function() X
setinverse <- function(Inverse) inverse <<- Inverse
getinverse <- function() inverse
list(set=set,get=get,setinverse=setinverse,getinverse=getinverse)
}
## Write a short comment describing this function
## calculate inverse of a matrix if it doesnt exist in the cache.
cacheSolve <- function(X, ...) {
## Return a matrix that is the inverse of 'x'
##We need corpor library for pseudoinverse function
if(require("corpcor")){
print("corpcor is loaded correctly")
} else {
print("trying to install corpcor")
install.packages("corpcor")
if(require(corpcor)){
print("corpcor installed and loaded")
} else {
stop("could not install corpcor")
}
}
inverse <- X$getinverse()
if(!is.null(inverse)){
message("matrix is in memory")
return(inverse)
}
message("inverse is not in memory so the inverse (if exist) is gonna be computed")
data <- X$get()
inverse <- pseudoinverse(data, ...)
X$setinverse(inverse)
inverse
}