This repository was archived by the owner on Jan 13, 2020. It is now read-only.
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
68 lines (56 loc) · 2.06 KB
/
cachematrix.R
File metadata and controls
68 lines (56 loc) · 2.06 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
61
62
63
64
65
66
67
68
## Matrix inversion can be a costly operation, especially if the same matrix is
## inverted over and over again. To avoid computing inverses which already have
## been solved, this file provided two methods:
##
## makeCacheMatrix: Will create a cache matrix which can store a matix as well
## as the corresponding inverse.
## cacheSolve: Will check if the input cache matrix has already been solved and
## return the cached version if possible. Else it will solve it and
## store the result in its internal cache.
# Creates a cache matrix capable of caching its inverse. The returned cache matrix
# will contain four methods: setmatrix, getmatrix, setinverse, and getinverse.
#
# Args:
# m: The non-inversed matrix (must be a matix)
#
# Returns:
# The cache matrix initialized to the given input matrix.
makeCacheMatrix <- function(m = matrix()) {
## variables
inverse <- NULL
## functions
setmatrix <- function(y) {
m <<- y
inverse <<- NULL
}
getmatrix <- function() m
setinverse <- function(y) inverse <<- y
getinverse <- function() inverse
## return the list of functions for the cache matrix
list(setmatrix = setmatrix,
getmatrix = getmatrix,
setinverse = setinverse,
getinverse = getinverse)
}
# Returns the inverse matrix for the given cache matrix. If the inverse has
# already been computed it will return the previous computed value, else it
# will compute the value and store it. The inverse is calculated with the
# solve function.
#
# Args:
# m : A cache matrix created with "makeCacheMatrix"
# ...: Any additional parameters will be handed into the solve function.
#
# Returns:
# The inverse matrix for the given input.
cacheSolve <- function(m, ...) {
inverse <- m$getinverse()
if(is.null(inverse)) { ## check if the inverse has been cached
message("No cached data available...calling solve..")
## use solve for the inverse and store it in matrix
org <- m$getmatrix()
inverse <- solve(org, ...)
m$setinverse(inverse)
}
inverse
}