|
1 |
| -## Put comments here that give an overall description of what your |
2 |
| -## functions do |
| 1 | +# Coursera - R Programming - Programming Assignment 2 |
| 2 | +# Caching the Inverse of a Matrix |
3 | 3 |
|
4 |
| -## Write a short comment describing this function |
| 4 | +# makeCacheMatrix: This function creates a special "matrix" object that can |
| 5 | +# cache its inverse |
5 | 6 |
|
6 | 7 | makeCacheMatrix <- function(x = matrix()) {
|
7 |
| - |
| 8 | + m <- NULL |
| 9 | + set <- function(y) { |
| 10 | + x <<- y |
| 11 | + m <<- NULL |
| 12 | + } |
| 13 | + get <- function() x |
| 14 | + setsolve <- function(solve) m <<- solve |
| 15 | + getsolve <- function() m |
| 16 | + list(set = set, get = get, |
| 17 | + setsolve = setsolve, |
| 18 | + getsolve = getsolve) |
8 | 19 | }
|
9 | 20 |
|
10 |
| - |
11 |
| -## Write a short comment describing this function |
| 21 | +# cacheSolve: This function computes the inverse of the special "matrix" |
| 22 | +# returned by makeCacheMatrix above. If the inverse has already been |
| 23 | +# calculated (and the matrix has not changed), then the cachesolve should |
| 24 | +# retrieve the inverse from the cache. |
12 | 25 |
|
13 | 26 | cacheSolve <- function(x, ...) {
|
14 |
| - ## Return a matrix that is the inverse of 'x' |
| 27 | + ## Return a matrix that is the inverse of 'x' |
| 28 | + m <- x$getsolve() |
| 29 | + if(!is.null(m)) { |
| 30 | + message("getting cached data") |
| 31 | + return(m) |
| 32 | + } |
| 33 | + data <- x$get() |
| 34 | + m <- solve(data, ...) |
| 35 | + x$setsolve(m) |
| 36 | + m |
15 | 37 | }
|
| 38 | + |
| 39 | +# Tested as follows: |
| 40 | +# m1 <- matrix(c(1,2,3,4), nrow = 2, ncol = 2) |
| 41 | +# m2 <- matrix(c(10, 9, 8, 7), nrow = 2, ncol = 2) |
| 42 | +# cm <- makeCacheMatrix(m1) |
| 43 | +# cacheSolve(cm) # doesn't use cache, returns solve(m1) |
| 44 | +# cacheSolve(cm) # returns cached result |
| 45 | +# cm$set(m2) |
| 46 | +# cacheSolve(cm) # doesn't use cache, returns solve(m2) |
| 47 | +# cacheSolve(cm) # returns cached result |
0 commit comments