forked from rdpeng/ProgrammingAssignment2
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcachematrix.R
82 lines (68 loc) · 1.7 KB
/
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
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
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
## Script to cache inverse of given Matrix
## Prepared for assignment 2
## Uses
## > mat = makeCacheMatrix(matrix(1:4, 2, 2))
## > mat$get()
## [,1] [,2]
## [1,] 1 3
## [2,] 2 4
##
## > mat$getinverse()
## NULL
##
## > cacheSolve(mat)
## [,1] [,2]
## [1,] -2 1.5
## [2,] 1 -0.5
##
## > cacheSolve(mat)
## Getting cached matrix
## [,1] [,2]
## [1,] -2 1.5
## [2,] 1 -0.5
#' Creates a spacial matrix and can cache its inverse
#'
#' @param mat A matrix or defaulted to blank 1,1 matrix.
#' @return A special matrix object
#' @examples
#' makeCacheMatrix(matrix(1:4, nrow = 2, ncol = 2))
makeCacheMatrix <- function(mat = matrix()) {
invMatrix <- NULL
#' Sets Matrix to mat and invalidates cache
#' @param matx A matrix
#' @return NULL
set <- function(matx) {
mat <<- matx
invMatrix <<- NULL
}
#' Returns current matrix
#' @param matx A matrix
#' @return matrix
get <- function() mat
#' caches passed inverse of current matrix
#' @param inv Inverted matrix
setinverse <- function(inv){
invMatrix <<- inv
}
#' Returns inverse of current matrix, if set
#' @return invMatrix
getinverse <- function() invMatrix
list(set = set, get = get,
setinverse = setinverse,
getinverse = getinverse)
}
#' Get cached inverse Matrix else Computes inverse of given matrix (if invertible),
#' saves it and returns
#' @param A special matrix object, created by makeCacheMatrix
#' @return inverse of Matrix
cacheSolve <- function(mat, ...) {
matx <- mat$getinverse()
if(!is.null(matx)) {
message("Getting cached matrix")
return(matx)
}
origMat <- mat$get()
invMat <- solve(origMat, ...)
mat$setinverse(invMat)
invMat
}