Skip to content

Commit c0de414

Browse files
committed
commit and submit cachematrix.R
1 parent e4eed41 commit c0de414

File tree

1 file changed

+50
-8
lines changed

1 file changed

+50
-8
lines changed

cachematrix.R

Lines changed: 50 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -1,15 +1,57 @@
1-
## Put comments here that give an overall description of what your
2-
## functions do
1+
## Caching the inverse of a matrix
32

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.
55

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.
713

8-
}
914

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+
}
1033

11-
## Write a short comment describing this function
1234

1335
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

Comments
 (0)