|
1 | 1 | ## Put comments here that give an overall description of what your
|
2 | 2 | ## functions do
|
| 3 | +# |
| 4 | +# makeCacheMatrix creates a special "matrix", which is really a list |
| 5 | +# containing functions to |
| 6 | +# |
| 7 | +# 1 set the value of the matrix |
| 8 | +# 2 get the value of the matrix |
| 9 | +# 3 set the value of the inverse |
| 10 | +# 4 get the value of the inverse |
| 11 | +# |
| 12 | +# cacheSolve solve the inverse of the input "matrix", in the manner that |
| 13 | +# |
| 14 | +# 1. return the cached inverse if the cache is not NULL |
| 15 | +# 2. calculate the inverse with solve if the cache is NULL, set it to the cache, |
| 16 | +# and then return it |
| 17 | +# |
| 18 | +# Example: |
| 19 | +# > A<-matrix(c(1,2,3,4),c(2,2)) |
| 20 | +# > B<-makeCacheMatrix(A) |
| 21 | +# > B$get() |
| 22 | +# [,1] [,2] |
| 23 | +# [1,] 1 3 |
| 24 | +# [2,] 2 4 |
| 25 | +# > cacheSolve(B) |
| 26 | +# [,1] [,2] |
| 27 | +# [1,] -2 1.5 |
| 28 | +# [2,] 1 -0.5 |
| 29 | +# > cacheSolve(B) |
| 30 | +# getting cached data |
| 31 | +# [,1] [,2] |
| 32 | +# [1,] -2 1.5 |
| 33 | +# [2,] 1 -0.5 |
| 34 | +# |
| 35 | + |
| 36 | + |
3 | 37 |
|
4 | 38 | ## Write a short comment describing this function
|
| 39 | +# |
| 40 | +# creates a special "matrix", which is really a list |
| 41 | +# of the following functions |
| 42 | +# |
| 43 | +# set(y) set y as the data of the matrix |
| 44 | +# get() : get the data of the matrix |
| 45 | +# setinverse(): set the value of the inverse |
| 46 | +# getinverse(): get the value of the inverse |
| 47 | +# |
| 48 | +# arguments: |
| 49 | +# x is a matrix to be set as the "data" of the special matrix |
5 | 50 |
|
6 | 51 | makeCacheMatrix <- function(x = matrix()) {
|
| 52 | + inv <- NULL |
| 53 | + set <- function(y){ |
| 54 | + x <<- y |
| 55 | + } |
| 56 | + get <- function() x |
7 | 57 |
|
| 58 | + setinverse <- function(inverse){ |
| 59 | + inv <<-inverse |
| 60 | + } |
| 61 | + getinverse <- function() inv |
| 62 | + |
| 63 | + list(set = set, get=get, setinverse = setinverse, getinverse=getinverse) |
| 64 | + |
8 | 65 | }
|
9 | 66 |
|
10 | 67 |
|
11 | 68 | ## Write a short comment describing this function
|
| 69 | +# |
| 70 | +# return the cached inverse and print a message, |
| 71 | +# calculate the inverse with solve and set it to the cache otherwise |
| 72 | +# |
| 73 | +# arguments: |
| 74 | +# x is a special matrix created by makeCacheMatrix |
| 75 | +# ... is the other options that will be passed to "solve" |
| 76 | +# |
12 | 77 |
|
13 | 78 | cacheSolve <- function(x, ...) {
|
14 | 79 | ## Return a matrix that is the inverse of 'x'
|
| 80 | + inv <- x$getinverse() |
| 81 | + if(!is.null(inv)){ |
| 82 | + message("getting cached data") |
| 83 | + } |
| 84 | + else{ |
| 85 | + data <- x$get() |
| 86 | + inv <- solve(data,...) |
| 87 | + x$setinverse(inv) |
| 88 | + } |
| 89 | + inv |
15 | 90 | }
|
0 commit comments