|
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 | +## cachematrix - R functions to compute and cache inverse of a Matrix |
| 2 | +## |
| 3 | +## Written by John Kinsella for Coursera class "R Programming" |
| 4 | +## |
5 | 5 |
|
| 6 | +## Function representing a matrix object |
| 7 | +## capable of caching it's inverse value |
| 8 | +## |
| 9 | +## Usage: |
| 10 | +## myMatrix <- makeCacheMatrix(x) |
| 11 | +## Arguments: |
| 12 | +## x - matrix value to initially store |
| 13 | +## Returns: |
| 14 | +## Returns a list of 4 functions related to the matrix: |
| 15 | +## * set(newValue) - set new value for matrix |
| 16 | +## * get() - get the current matrix value |
| 17 | +## * setInverse(inverseMatrix) - set the inverse matrix value |
| 18 | +## * getInverse() - get the inverse of current matrix if set, NULL otherwise |
6 | 19 | makeCacheMatrix <- function(x = matrix()) {
|
| 20 | + inverseMatrix <- NULL |
| 21 | + |
| 22 | + set <- function(newValue) { |
| 23 | + x <<- newValue |
| 24 | + inverseMatrix <<- NULL |
| 25 | + } |
| 26 | + get <- function() x |
| 27 | + setinverse <- function(targetInverse) inverseMatrix <<- targetInverse |
| 28 | + getinverse <- function() inverseMatrix |
7 | 29 |
|
| 30 | + list(set=set, get=get, setinverse=setinverse, getinverse=getinverse) |
8 | 31 | }
|
9 | 32 |
|
| 33 | +## Computes inverse of matrix. If inverse was already calculated, returns cached |
| 34 | +## value. |
| 35 | +## |
| 36 | +## Usage: |
| 37 | +## invertedMatrix <- cacheSolve(x) |
| 38 | +## Arguments: |
| 39 | +## x - list generated by makeCacheMatrix() |
| 40 | +## Returns: |
| 41 | +## inverted version of matrix in x. |
| 42 | +cacheSolve <- function(x, ...) { |
| 43 | + inverseMatrix <- x$getinverse() |
10 | 44 |
|
11 |
| -## Write a short comment describing this function |
| 45 | + # If matrix inverse has been calculated, returned cached value |
| 46 | + if(!is.null(inverseMatrix)) { |
| 47 | + message("Getting cached data") |
| 48 | + return(inverseMatrix) |
| 49 | + } |
12 | 50 |
|
13 |
| -cacheSolve <- function(x, ...) { |
14 |
| - ## Return a matrix that is the inverse of 'x' |
| 51 | + # If not cached already, calculate inverse and return |
| 52 | + data <- x$get() |
| 53 | + inverseMatrix <- solve(data) |
| 54 | + x$setinverse(inverseMatrix) |
| 55 | + inverseMatrix |
15 | 56 | }
|
0 commit comments