|
1 | 1 | ## Put comments here that give an overall description of what your
|
2 | 2 | ## functions do
|
| 3 | +## Peer Assessment / Programming Assignment 2 / R Programming course |
3 | 4 |
|
4 |
| -## Write a short comment describing this function |
| 5 | +## This function creates a special "matrix" object that can cache its inverse. |
5 | 6 |
|
6 |
| -makeCacheMatrix <- function(x = matrix()) { |
| 7 | +makeCacheMatrix <- function(matrix = matrix()) { |
| 8 | + ## Return a special "matrix" that is the inverse of 'x', which is really a list containing a function to |
| 9 | + ## 1. set the value of the matrix |
| 10 | + ## 2. set the value of another matrix (is inverse) |
| 11 | + ## 3. get the value of the matrix |
| 12 | + ## 4. get the value of the matrix inverse |
7 | 13 |
|
| 14 | + inverse <- NULL |
| 15 | + |
| 16 | + setmatrix <- function(y) { |
| 17 | + matrix <<- y |
| 18 | + inverse <<- NULL |
| 19 | + } |
| 20 | + |
| 21 | + setinverse <- function(y) { |
| 22 | + inverse <<- y |
| 23 | + } |
| 24 | + |
| 25 | + getmatrix <- function () matrix |
| 26 | + |
| 27 | + getinverse <- function () inverse |
| 28 | + |
| 29 | + list(setmatrix=setmatrix, setinverse=setinverse, |
| 30 | + getmatrix=getmatrix, getinverse=getinverse) |
8 | 31 | }
|
9 | 32 |
|
10 | 33 |
|
11 |
| -## Write a short comment describing this function |
| 34 | +## This function computes the inverse of the special "matrix" returned by makeCacheMatrix above. |
| 35 | +## If the inverse has already been calculated (and the matrix has not changed), then the cacheSolve |
| 36 | +## should retrieve the inverse from the cache. |
12 | 37 |
|
13 | 38 | cacheSolve <- function(x, ...) {
|
14 |
| - ## Return a matrix that is the inverse of 'x' |
| 39 | + ## Return a matrix that is the inverse of 'x' |
| 40 | + |
| 41 | + matrix <- x$getmatrix() |
| 42 | + inverse <- x$getinverse() |
| 43 | + |
| 44 | + if(!is.null(inverse)) { |
| 45 | + message("getting cached data") |
| 46 | + return(inverse) |
| 47 | + } |
| 48 | + |
| 49 | + inverse <- solve(matrix) |
| 50 | + x$setmatrix(matrix) |
| 51 | + x$setinverse(inverse) |
| 52 | + inverse |
15 | 53 | }
|
0 commit comments