|
1 |
| -## Put comments here that give an overall description of what your |
2 |
| -## functions do |
| 1 | +## The goal of this pair of functions is to cache the inverse of a matrix. |
3 | 2 |
|
4 |
| -## Write a short comment describing this function |
5 | 3 |
|
6 |
| -makeCacheMatrix <- function(x = matrix()) { |
7 | 4 |
|
| 5 | +## makeVector creates a special "matrix", which is really a matrix containing a function to |
| 6 | +## set the value of the squared matrix |
| 7 | +## get the value of the squared matrix |
| 8 | +## set the value of the inverse of the matrix |
| 9 | +## get the value of the inverse of the matrix |
| 10 | + |
| 11 | +makeCacheMatrix <- function(m = matrix()) { |
| 12 | + inv <- NULL |
| 13 | + set <- function(y) { |
| 14 | + m <<- y |
| 15 | + inv <<- NULL |
| 16 | + } |
| 17 | + get <- function() m |
| 18 | + setinverse <- function(inverse) inv <<- inverse |
| 19 | + getinverse <- function() inv |
| 20 | + |
| 21 | + list(set = set, get = get, |
| 22 | + setinverse = setinverse, |
| 23 | + getinverse = getinverse) |
8 | 24 | }
|
9 | 25 |
|
10 | 26 |
|
11 |
| -## Write a short comment describing this function |
| 27 | +## cacheSolve function calculates the inverse of the matrix created with the makeCacheMatrix function. |
| 28 | +## However, it first checks to see if the inverse of the matrix has already been calculated. |
| 29 | +## If so, it gets the inverse of the matrix from the cache and skips the computation. |
| 30 | +## Otherwise, it calculates the inverse of the matrix and sets the value of the inverse in the cache via the setinverse function. |
12 | 31 |
|
13 |
| -cacheSolve <- function(x, ...) { |
14 |
| - ## Return a matrix that is the inverse of 'x' |
| 32 | +cacheSolve <- function(m) { |
| 33 | + ## Return a matrix that is the inverse of 'm' |
| 34 | + inv <- m$getinverse() |
| 35 | + if(!is.null(inv)) { |
| 36 | + message("getting cached data") |
| 37 | + return(inv) |
| 38 | + } |
| 39 | + data <- m$get() |
| 40 | + inv <- solve(data) |
| 41 | + m$setinverse(inv) |
| 42 | + inv |
| 43 | + |
15 | 44 | }
|
| 45 | + |
| 46 | + |
| 47 | +## This code is used just for test purpose |
| 48 | +## m <- makeCacheMatrix(matrix(1:4,2,2)) |
| 49 | +## t <- cacheSolve(m) |
0 commit comments