|
1 |
| -## Put comments here that give an overall description of what your |
2 |
| -## functions do |
| 1 | +## To speed performing repeated inversions of matrices, the functions |
| 2 | +## below will cache the first inversion and return the contents |
| 3 | +## of the cache for repeated calls. |
3 | 4 |
|
4 |
| -## Write a short comment describing this function |
| 5 | +## Creates a list that has functions to set a matrix, get the matrix, |
| 6 | +## set the inverse of the matrix, and get the inverse of the matrix. |
5 | 7 |
|
6 | 8 | makeCacheMatrix <- function(x = matrix()) {
|
7 |
| - |
| 9 | + inverse <- NULL |
| 10 | + set <- function(y) { |
| 11 | + x <<- y |
| 12 | + inverse <<- NULL |
| 13 | + } |
| 14 | + get <- function() x |
| 15 | + setinverse <- function(i) inverse <<- i |
| 16 | + getinverse <- function() inverse |
| 17 | + list(set=set, get=get, setinverse=setinverse, getinverse=getinverse) |
8 | 18 | }
|
9 | 19 |
|
10 | 20 |
|
11 |
| -## Write a short comment describing this function |
| 21 | +## Computes the inverse of a "matrix" object created by makeCacheMatrix. |
| 22 | +## If the inverse has already been calculated, it will be returned |
| 23 | +## from the cache. |
12 | 24 |
|
13 | 25 | cacheSolve <- function(x, ...) {
|
14 |
| - ## Return a matrix that is the inverse of 'x' |
| 26 | + inverse <- x$getinverse() |
| 27 | + if(!is.null(inverse)) { |
| 28 | + message("getting cached data") |
| 29 | + return(inverse) |
| 30 | + } |
| 31 | + data <- x$get() |
| 32 | + inverse <- solve(data, ...) |
| 33 | + x$setinverse(inverse) |
| 34 | + inverse |
15 | 35 | }
|
| 36 | + |
| 37 | +## My test of the functions: |
| 38 | +# |
| 39 | +# > source("cachematrix.R") |
| 40 | +# > mcm <- makeCacheMatrix(x=matrix(c(4,7,2,6), nrow=2, ncol=2, byrow=T)) |
| 41 | +# > cacheSolve(mcm) |
| 42 | + #[,1] [,2] |
| 43 | +# [1,] 0.6 -0.7 |
| 44 | +# [2,] -0.2 0.4 |
| 45 | +# > cacheSolve(mcm) |
| 46 | +# getting cached data |
| 47 | + #[,1] [,2] |
| 48 | +# [1,] 0.6 -0.7 |
| 49 | +# [2,] -0.2 0.4 |
| 50 | + |
0 commit comments