|
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. |
3 | 5 |
|
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. |
5 | 24 |
|
6 | 25 | 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) |
7 | 37 |
|
8 | 38 | }
|
9 | 39 |
|
10 | 40 |
|
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. |
12 | 45 |
|
13 | 46 | cacheSolve <- function(x, ...) {
|
14 | 47 | ## 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 |
15 | 57 | }
|
0 commit comments