Skip to content

Commit 2cf9195

Browse files
committed
Update function and add comments for programming assignment 2
1 parent 7f657dd commit 2cf9195

File tree

1 file changed

+46
-7
lines changed

1 file changed

+46
-7
lines changed

cachematrix.R

Lines changed: 46 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -1,15 +1,54 @@
1-
## Put comments here that give an overall description of what your
2-
## functions do
1+
## These functions are to speed up the process of inversing a matrix. This is
2+
## done by creating a special object to "cache" the matrix. The function makeCacheMatrix
3+
## must be run first for this assignment to create that special object. If the
4+
## original matrix is changed, the makeCacheMatrix *must* be run again to
5+
## accurately contain the inverse.
36

4-
## Write a short comment describing this function
7+
## This function assumes the given matrix will always be inversible.
58

9+
## This function creates a special "matrix" object that can cache its inverse.
610
makeCacheMatrix <- function(x = matrix()) {
7-
11+
m <- NULL
12+
## matrix is cleared to create new special "matrix" object and setting matrix
13+
set <- function(y) {
14+
x <<- y
15+
m <<- NULL
16+
}
17+
get <- function() x
18+
19+
## set the inverse of the matrix by rebinding
20+
## setmatrix in the parent of the current environment.
21+
setmatrix <- function(solve) m <<- solve
22+
getmatrix <- function() m
23+
24+
## create list for all functions
25+
list(set = set, get = get,
26+
setmatrix = setmatrix,
27+
getmatrix = getmatrix)
828
}
929

1030

11-
## Write a short comment describing this function
12-
31+
## This function computes the inverse of the special "matrix" returned by
32+
## makeCacheMatrix above. If the inverse has already been calculated (and
33+
## the matrix has not changed), then cacheSolve should retrieve the inverse
34+
## from the cache.
1335
cacheSolve <- function(x, ...) {
14-
## Return a matrix that is the inverse of 'x'
36+
## gets the matrix from cache if it exists
37+
m <- x$getmatrix()
38+
39+
## check if matrix exists in special object cache
40+
if(!is.null(m)) {
41+
message("getting cached data")
42+
## Return a matrix that is the inverse of 'x' that was stored in
43+
## "special matrix" object when it was created
44+
return(m)
45+
}
46+
## the inverse matrix was not previously stored so we need to set it
47+
data <- x$get()
48+
## compute the inverse of the special matrix with given data
49+
m <- solve(data, ...)
50+
## set new m
51+
x$setmatrix(m)
52+
## output the new m value
53+
m
1554
}

0 commit comments

Comments
 (0)