Skip to content

Commit 8e6d3ef

Browse files
committed
Added the code to get/set the matrices and solve (inverse) them.
1 parent 7f657dd commit 8e6d3ef

File tree

1 file changed

+46
-4
lines changed

1 file changed

+46
-4
lines changed

cachematrix.R

Lines changed: 46 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,15 +1,57 @@
1-
## Put comments here that give an overall description of what your
2-
## functions do
1+
## These functions cache the inverse of a matrix. makeMatrixCache
2+
## creates an object that will get a cached matrix or store a
3+
## matrix in the cache.
4+
## cacheSolve is the way to interact with matrix cache.
35

4-
## Write a short comment describing this function
6+
## Example usage:
7+
## c=rbind(c(1, -1/4), c(-1/4, 1))
8+
## > c=rbind(c(1, -1/4), c(-1/4, 1))
9+
## > c
10+
## > d<-makeCacheMatrix(c)
11+
12+
## [,1] [,2]
13+
## [1,] 1.00 -0.25
14+
## [2,] -0.25 1.00
15+
16+
## > cacheSolve(d)
17+
## [,1] [,2]
18+
## [1,] 1.0666667 0.2666667
19+
## [2,] 0.2666667 1.0666667
20+
21+
22+
## This function creates a special "matrix" object
23+
## that can cache its inverse.
524

625
makeCacheMatrix <- function(x = matrix()) {
26+
m <- NULL
27+
set <- function(y) {
28+
x <<- y
29+
m <<- NULL
30+
}
31+
get <- function() x
32+
setinv <- function(mean) m <<- mean
33+
getinv <- function() m
34+
list(set = set, get = get,
35+
setinv = setinv,
36+
getinv = getinv)
737

838
}
939

1040

11-
## Write a short comment describing this function
41+
## This function computes the inverse of the special
42+
## "matrix" returned by `makeCacheMatrix` above. If the inverse has
43+
## already been calculated (and the matrix has not changed), then
44+
## `cacheSolve` should retrieve the inverse from the cache.
1245

1346
cacheSolve <- function(x, ...) {
1447
## Return a matrix that is the inverse of 'x'
48+
m <- x$getinv()
49+
if(!is.null(m)) {
50+
message("getting cached data")
51+
return(m)
52+
}
53+
data <- x$get()
54+
m <- solve(data, ...)
55+
x$setinv(m)
56+
m
1557
}

0 commit comments

Comments
 (0)