1
- # # Put comments here that give an overall description of what your
2
- # # functions do
1
+ # # Caching the inverse of a matrix
3
2
4
- # # Write a short comment describing this function
3
+ # # This function creates a special "matrix" object that can cache its inverse.
4
+ # # Below are two functions.
5
5
6
- makeCacheMatrix <- function (x = matrix ()) {
6
+ # # makeCacheMatrix is used to create a special object that stores a matrix
7
+ # # and cache's its inverse.
8
+
9
+ # # The cacheSolve function computes the inverse of the special "matrix"
10
+ # # returned by makeCacheMatrix above.
11
+ # # If the inverse has already been calculated (and the matrix has not changed),
12
+ # # then the cachesolve should retrieve the inverse from the cache.
7
13
8
- }
9
14
15
+ makeCacheMatrix <- function (x = matrix ()) {
16
+ m <- NULL
17
+ # The set function sets the value of the matrix
18
+ set <- function (k ) {
19
+ x <<- k
20
+ m <<- NULL
21
+ }
22
+ # The get function gets the value of the vector
23
+ get <- function () x
24
+ # Solve the inverse matrix of x
25
+ setinverse <- function (solve ) m <<- solve
26
+ # Get the list of matrix in a list
27
+ getinverse <- function () m
28
+ list (set = set , get = get ,
29
+ setinverse = setinverse ,
30
+ getinverse = getinverse )
31
+
32
+ }
10
33
11
- # # Write a short comment describing this function
12
34
13
35
cacheSolve <- function (x , ... ) {
14
- # # Return a matrix that is the inverse of 'x'
15
- }
36
+ m <- x $ getinverse()
37
+ if (! is.null(m )) {
38
+ message(" getting cached data" )
39
+ return (m )
40
+ }
41
+ data <- x $ get()
42
+ m <- solve(data ,... )
43
+ x $ setinverse(m )
44
+ m
45
+ }
46
+
47
+ # # Test this function.
48
+ # # Step 1. define a matrix
49
+ mm = matrix (c(1 ,2 ,3 ,1 ), nrow = 2 ,ncol = 2 )
50
+ # # Step 2. define a specific matrix x that contains the output from
51
+ x <- makeCacheMatrix(mm )
52
+ # # Step 3. For debug reason, check whether the determinant det(mm) is zero or not
53
+ det(mm )
54
+ # # This should generate the first-time output
55
+ cacheSolve(x )
56
+ # # This should return the generated value in the previous command
57
+ cacheSolve(x )
0 commit comments