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
60 lines (39 loc) · 1.48 KB
/
cachematrix.R
File metadata and controls
60 lines (39 loc) · 1.48 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
## Put comments here that give an overall description of what your
## functions do
## Write a short comment describing this function
makeCacheMatrix <- function(x = matrix()) {
# ERROR MESSAGES
#1 if matrix is not square
if(nrow(x)!=ncol(x)) {stop("The matrix is not square")}
#2 if matrix is all NA
if(all(is.na(x))){stop("Cannot compute inverse of NA matrix")}
#3 if matrix has determinant 0
if(det(x)==0){stop("The matrix has a determinant of 0")}
# creates a square matrix with all NA as a null matrix
null_matrix <- function(x){
nm <- matrix(NA,nrow(x),ncol(x))
return(nm)
}
inv <- null_matrix(x)
set <- function(y){
x <<- y
inv <<- NULL
}
get <- function() x
setinv <- function(inverse) inv <<- inverse
getinv <- function() inv
list(set=set,get=get,setinv=setinv,getinv=getinv)
}
## Write a short comment describing this function
cacheSolve <- function(x, ...) {
## Return a matrix that is the inverse of 'x'
inv <- x$getinv()
if(!all(is.na(inv))){
message("getting cached data")
return(inv)
}
data <- x$get()
inv <- solve(data,...)
x$setinv(inv)
return(inv)
}