|
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 | +## r-prog programming assignment 2 |
| 2 | +## |
| 3 | +## This module defines functions for solving matrices |
| 4 | +## optimized for repeated access via caching. |
| 5 | +## |
| 6 | +## Example usage: |
| 7 | +## $ source("cachematrix.R") |
| 8 | +## $ m <- matrix(c(1,2,3, 11), nrow = 2, ncol = 2) |
| 9 | +## $ cm <- makeCacheMatrix(m) |
| 10 | +## $ cm$getinverse() #returns NULL |
| 11 | +## $ cacheSolve(cm) #returns inverse |
| 12 | +## $ cm$getinverse() #returns cached inverse |
| 13 | +## |
| 14 | +## Notes: |
| 15 | +## * Current implementation will cache results of first |
| 16 | +## invocation of `cacheSolve`. If subsequent calls to |
| 17 | +## `cacheSolve`, are made with different extra parameters, |
| 18 | +## incorrect results could be returned. |
5 | 19 |
|
| 20 | +## Creates a cache matrix, an object suitable |
| 21 | +## for use with `cacheSolve`. |
6 | 22 | makeCacheMatrix <- function(x = matrix()) {
|
7 |
| - |
| 23 | + i <- NULL |
| 24 | + set <- function(y) { |
| 25 | + x <<- y |
| 26 | + i <<- NULL |
| 27 | + } |
| 28 | + get <- function() x |
| 29 | + setinverse <- function(inverse) i <<- inverse |
| 30 | + getinverse <- function() i |
| 31 | + list(set = set, get = get, |
| 32 | + setinverse = setinverse, |
| 33 | + getinverse = getinverse) |
8 | 34 | }
|
9 | 35 |
|
10 |
| - |
11 |
| -## Write a short comment describing this function |
12 |
| - |
| 36 | +## Finds the inverse of provided cache matrix. Will return |
| 37 | +## cached results for the cache matrix if some are defined. |
13 | 38 | cacheSolve <- function(x, ...) {
|
14 |
| - ## Return a matrix that is the inverse of 'x' |
| 39 | + i <- x$getinverse() |
| 40 | + if(!is.null(i)) { |
| 41 | + message("getting cached data") |
| 42 | + return(i) |
| 43 | + } |
| 44 | + data <- x$get() |
| 45 | + i <- solve(data, ...) |
| 46 | + x$setinverse(i) |
| 47 | + i |
15 | 48 | }
|
0 commit comments