Skip to content

Commit be279a6

Browse files
committed
Upload
1 parent 7f657dd commit be279a6

File tree

1 file changed

+43
-6
lines changed

1 file changed

+43
-6
lines changed

cachematrix.R

Lines changed: 43 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1,15 +1,52 @@
1-
## Put comments here that give an overall description of what your
2-
## functions do
1+
## These functions allow one to calculate and cache a matrix inverse,
2+
## avoiding the need to recalculate the inverse if it is needed multiple times.
33

4-
## Write a short comment describing this function
4+
### Example:
5+
### > source("./cachematrix.R")
6+
### > mymat <- makeCacheMatrix(matrix(c(1,2,3,3,2,1,4,5,2),ncol=3,nrow=3))
7+
### > cacheSolve(mymat)
8+
### [,1] [,2] [,3]
9+
### [1,] -0.0625 -0.125 0.4375
10+
### [2,] 0.6875 -0.625 0.1875
11+
### [3,] -0.2500 0.500 -0.2500
12+
###
13+
### > cacheSolve(mymat)
14+
### getting cached data
15+
### [,1] [,2] [,3]
16+
### [1,] -0.0625 -0.125 0.4375
17+
### [2,] 0.6875 -0.625 0.1875
18+
### [3,] -0.2500 0.500 -0.2500
519

20+
21+
## This creates the matrix object that will store the cached inverse, and a method to calculate the inverse
622
makeCacheMatrix <- function(x = matrix()) {
23+
i <- NULL
24+
set <- function(y) {
25+
x <<- y
26+
i <<- NULL
27+
}
28+
get <- function() x
29+
setinv <- function(inv) i <<- inv
30+
getinv <- function() i
731

32+
return( list(set = set, get = get,
33+
setinv = setinv,
34+
getinv = getinv) )
835
}
936

1037

11-
## Write a short comment describing this function
12-
38+
## This function will return the inverse of a matrix, via the cached value if possible
1339
cacheSolve <- function(x, ...) {
14-
## Return a matrix that is the inverse of 'x'
40+
## Return a matrix that is the inverse of 'x'
41+
42+
i <- x$getinv()
43+
if(!is.null(i)) {
44+
message("getting cached data")
45+
return(i) #if we already cached inverse then return and stop here
46+
}
47+
#otherwise calculate and cache inverse
48+
data <- x$get()
49+
i <- solve(data, ...) #solve for inverse - R function
50+
x$setinv(i) #cache inverse
51+
return(i)
1552
}

0 commit comments

Comments
 (0)