Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Commit 3e5a566

Browse files
committed
Solution to Assignment rdpeng#2 Week rdpeng#3
This is my submitted solution to the invert matrix/store matrix in cache assignment.
1 parent 7f657dd commit 3e5a566

File tree

1 file changed

+68
-6
lines changed

1 file changed

+68
-6
lines changed

cachematrix.R

Lines changed: 68 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1,15 +1,77 @@
1-
## Put comments here that give an overall description of what your
2-
## functions do
1+
## OVERALL DESCRIPTION:
2+
3+
## These are two methods that will store an inputted
4+
## matrix into the cache and calculate it's inverse.
5+
## This is done so that when calculating the inverses
6+
## of a large vector or set of matrices, we only have
7+
## to perform each calculation once, and save
8+
## it for later.
9+
10+
11+
##DESCRIPTION OF makeCacheMatrix:
12+
13+
## This function stores the method's inputted
14+
## matrix in the cache for use later. It returns
15+
## a list of the available getter and setter
16+
## functions for the input matrix and its
17+
## inverse (from the cache).
318

4-
## Write a short comment describing this function
519

6-
makeCacheMatrix <- function(x = matrix()) {
720

21+
## Var i is the variable where the matrix will be
22+
## stored (ie: the cache).
23+
## setMat stores the input matrix
24+
## getMat retrieves the input matrix
25+
## setInv sets the inverse matrix into the cache.
26+
## getInv returns the inverse matrix
27+
28+
## This is copied from Roger Peng's supplied code
29+
## for the assignment. I have explained the lines
30+
## that I think are difficult to read.
31+
32+
makeCacheMatrix <- function(x = matrix()) {
33+
i <- NULL #makes sure cache is clear
34+
35+
setMat <- function(y) {
36+
x <<- y ##inputs the matrix.
37+
i <<- NULL ##So, again the cache is set to empty
38+
}
39+
40+
getMat <- function() x
41+
##prints the input matrix
42+
43+
setInv <- function(inv) i <<- inv
44+
##stores the inverse matrix in the cache
45+
getInv <- function() i
46+
##prints the inverse matrix
47+
list(setMat = setMat, getMat = getMat,
48+
setInv = setInv,
49+
getInv = getInv
50+
)
851
}
952

53+
##DESCRIPTION OF cacheSolve:
1054

11-
## Write a short comment describing this function
55+
## This function solves for the inverse of
56+
## an inputted matrix. It uses the function above
57+
## to store and retrieve both the input matrix and
58+
## the inverse matrix
1259

1360
cacheSolve <- function(x, ...) {
14-
## Return a matrix that is the inverse of 'x'
61+
## Return a matrix that is the inverse of 'x'
62+
63+
invMat <- x$getInv()
64+
65+
if(!is.null(i)) {
66+
message("getting cached data")
67+
return(i)
68+
}
69+
70+
data <- x$getMat()
71+
invMat <- solve(data)
72+
x$setInv(invMat)
73+
74+
invMat
1575
}
76+
77+
## Thanks for reading! :)

0 commit comments

Comments
 (0)