|
1 |
| -## Put comments here that give an overall description of what your |
2 |
| -## functions do |
3 |
| - |
4 |
| -## Write a short comment describing this function |
5 |
| - |
6 |
| -makeCacheMatrix <- function(x = matrix()) { |
| 1 | +## This file contains a pair of R functions that cache the inverse of a matrix. |
| 2 | +## This is part of a peer assessment for the second programming assignment in the Coursera "R Programming" course. |
7 | 3 |
|
| 4 | +## The function makeCacheMatrix creates a special "matrix object", which is really a list containing |
| 5 | +## a function to set the matrix; |
| 6 | +## a function to get the matrix; |
| 7 | +## a function to set the inverse of the matrix; |
| 8 | +## a function to get the inverse of the matrix. |
| 9 | + makeCacheMatrix <- function(x = matrix()) { |
| 10 | + |
| 11 | + ## 0. nulls the inverse matrix |
| 12 | + m <- NULL |
| 13 | + |
| 14 | + ## 1. definition the function that sets the matrix |
| 15 | + set <- function(y) { |
| 16 | + x <<- y |
| 17 | + m <<- NULL |
| 18 | + } |
| 19 | + |
| 20 | + ## 2. definition the function that gets the matrix |
| 21 | + get <- function() x |
| 22 | + |
| 23 | + ## 3. definition the function that sets the inverse of the matrix |
| 24 | + setinverse <- function(solve) m <<- solve |
| 25 | + |
| 26 | + ## 4. definition the function that gets the inverse of the matrix |
| 27 | + getinverse <- function() m |
| 28 | + |
| 29 | + ## returns the list of functions defined above |
| 30 | + list(set = set, get = get, |
| 31 | + setinverse = setinverse, |
| 32 | + getinverse = getinverse) |
8 | 33 | }
|
9 | 34 |
|
10 | 35 |
|
11 |
| -## Write a short comment describing this function |
| 36 | +## The function cacheSolve checks to see if the inverse matrix has already been calculated. |
| 37 | +## If not, it gets the inverse matrix from the cache. |
| 38 | +## Otherwise, it calculates the inverse matrix of the special "matrix object" created with the above function and returns it. |
| 39 | +## The argument should be a "matrix object" of the type defined above |
| 40 | + cacheSolve <- function(x, ...) { |
12 | 41 |
|
13 |
| -cacheSolve <- function(x, ...) { |
14 |
| - ## Return a matrix that is the inverse of 'x' |
| 42 | + ## 0. gets the inverse matrix from the "matrix object" x |
| 43 | + m <- x$getinverse() |
| 44 | + |
| 45 | + ## 1. if the inverse matrix already exists, returns it |
| 46 | + if(!is.null(m)) { |
| 47 | + message("getting cached data") |
| 48 | + return(m) |
| 49 | + } |
| 50 | + |
| 51 | + ## 2. otherwise, gets the matrix from the "matrix object" |
| 52 | + data <- x$get() |
| 53 | + |
| 54 | + ## 3. calculates the inverse matrix |
| 55 | + m <- solve(data, ...) |
| 56 | + |
| 57 | + ## 4. saves the calculated inverse matrix in the "matrix object" |
| 58 | + x$setinverse(m) |
| 59 | + |
| 60 | + ## 5. return the inverse matrix |
| 61 | + m |
15 | 62 | }
|
0 commit comments