forked from rdpeng/ProgrammingAssignment2
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcachematrix.R
41 lines (33 loc) · 903 Bytes
/
cachematrix.R
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
## Basic caching functionality regarding inverse matrices.
## Creates a cachable matrix with a variable to store the inverse matrix
makeCacheMatrix <- function(x = matrix()) {
inverse <- NULL
get <- function() x
set <- function(m) {
x <<- m
inverse <<- NULL
}
getInverse <- function() inverse
setInverse <- function(matrix) inverse <<- matrix
list(get = get, set = set,
getInverse = getInverse,
setInverse = setInverse)
}
## Returns the inverse of a non-singular square CacheMatrix.
cacheSolve <- function(x, ...) {
m <- x$get();
if (ncol(m) != nrow(m)) {
stop("Non-square matrices cannot be inverted");
}
if(det(m) == 0) {
stop("Singular matrices cannot be inverted");
}
inv <- x$getInverse();
if(!is.null(inv)) {
message("Read cached matrix");
return(inv);
}
inv <- solve(m, ...);
x$setInverse(inv);
inv;
}