Skip to content

Commit 3f24534

Browse files
author
hide kojima
committed
Init Commit For assignment
Init imll for course assignment
1 parent 7f657dd commit 3f24534

File tree

1 file changed

+42
-8
lines changed

1 file changed

+42
-8
lines changed

cachematrix.R

Lines changed: 42 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -1,15 +1,49 @@
1-
## Put comments here that give an overall description of what your
2-
## functions do
3-
4-
## Write a short comment describing this function
1+
## makeCacheMatrix creates a special "vector",
2+
# which is really a list containing a function to
3+
# a) set the value of the matrix
4+
# b) get the value of the matrix
5+
# c) set the value of the inverse of the matrix
6+
# d) get the value of the inverse of the matrix
57

68
makeCacheMatrix <- function(x = matrix()) {
7-
9+
inv <- NULL
10+
## Update existing matrix
11+
set <- function(y){
12+
x <<- y
13+
inv <<- NULL
14+
}
15+
## Return original matrix
16+
get <- function() x
17+
### Set the inverse of the matrix
18+
setinverse <- function(inverse) inv <<- inverse
19+
### Return the inverse of the matrix
20+
getinverse <- function() inv
21+
list(set = set, get = get,
22+
setinverse = setinverse,
23+
getinverse = getinverse)
824
}
925

10-
11-
## Write a short comment describing this function
26+
## cacheSolve performs following tasks:
27+
# 1) check if inverse of the matrix is already created or not
28+
# 2) return the inverse of the matrix if cached inverse found
29+
# 3) compute inverse of the matrix if no cache found
30+
# 4) cache the inverse of the matrix
31+
# 5) return the inverse of the matrix
1232

1333
cacheSolve <- function(x, ...) {
14-
## Return a matrix that is the inverse of 'x'
34+
inv <- x$getinverse()
35+
## check if inverse of the matrix is cached
36+
if(!is.null(inv)) {
37+
## return cache if cache is found
38+
message("getting cached data")
39+
return(inv)
40+
}
41+
## if cache is not found, then get the inverse of the matrix.
42+
## first, get the original matrix
43+
data <- x$get()
44+
## then get a inverse
45+
inv <- solve(data, ...)
46+
### cache retrieved value
47+
x$setinverse(inv)
48+
inv
1549
}

0 commit comments

Comments
 (0)