Skip to content

Commit df0f48d

Browse files
author
Craig Ingram
committed
implemented makeCacheMatrix and cacheSolve functions
1 parent 7f657dd commit df0f48d

File tree

1 file changed

+45
-10
lines changed

1 file changed

+45
-10
lines changed

cachematrix.R

Lines changed: 45 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -1,15 +1,50 @@
1-
## Put comments here that give an overall description of what your
2-
## functions do
3-
4-
## Write a short comment describing this function
1+
## cacheSolve and makeCacheMatrix are used to cache matrix inverses, which can be expensive calculations.
2+
##
3+
## For example,
4+
##
5+
##> foo <- matrix(data = c(1.4,3,2,-6.7), nrow = 2, ncol = 2) # creates a 2x2 matrix
6+
##> x <- makeCacheMatrix(foo) # create a cache matrix
7+
##> cacheSolve(x) # cacheSolve the cache matrix, x
8+
##[,1] [,2]
9+
##[1,] 0.4356307 0.13003901
10+
##[2,] 0.1950585 -0.09102731
11+
##> cacheSolve(x) # cacheSolve the cache matrix, x. note the "getting cached data" message.
12+
##getting cached data
13+
##[,1] [,2]
14+
##[1,] 0.4356307 0.13003901
15+
##[2,] 0.1950585 -0.09102731
16+
##
517

18+
## makeCacheMatrix creates a special “matrix” object that can cache its inverse.
619
makeCacheMatrix <- function(x = matrix()) {
7-
20+
m <- NULL
21+
set <- function(y) {
22+
x <<- y
23+
m <<- NULL
24+
}
25+
get <- function() x
26+
setinv <- function(inv) m <<- inv
27+
getinv <- function() m
28+
list(
29+
set = set,
30+
get = get,
31+
setinv = setinv,
32+
getinv = getinv
33+
)
834
}
935

10-
11-
## Write a short comment describing this function
12-
36+
## cacheSolve computes the inverse of the special “matrix” returned by makeCacheMatrix. If a cached inverse cannot be found,
37+
## it calculates the inverse, saves the result in the CacheMatrix (x), and returns the result.
1338
cacheSolve <- function(x, ...) {
14-
## Return a matrix that is the inverse of 'x'
15-
}
39+
## Return a matrix that is the inverse of 'x'
40+
m <- x$getinv()
41+
if (!is.null(m)) {
42+
message("getting cached data")
43+
return(m)
44+
} else {
45+
data <- x$get()
46+
m <- solve(data)
47+
x$setinv(m)
48+
m
49+
}
50+
}

0 commit comments

Comments
 (0)