Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Commit f54dfa9

Browse files
committed
Implementing caching inverse matrix in R
1 parent 7f657dd commit f54dfa9

File tree

2 files changed

+70
-2
lines changed

2 files changed

+70
-2
lines changed

.Rhistory

Lines changed: 49 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,49 @@
1+
getwd()
2+
setwd("~/Documents/GitHub/ProgrammingAssignment2")
3+
}
4+
}
5+
ls
6+
makeCacheMatrix
7+
source("cachematrix.R")
8+
makeCacheMatrix(c(10))
9+
x <- matrix(1:6, 2, 3)
10+
x
11+
makeCacheMatrix(x)
12+
cacheSolve(x)
13+
cacheSolve(x, makeCacheMatrix(x))
14+
View(cacheSolve)
15+
View(cacheSolve)
16+
View(cacheSolve)
17+
View(makeCacheMatrix)
18+
makeCacheMatrix <- function(x = matrix()) {
19+
## functions do
20+
## Write a short comment describing this function
21+
makeCacheMatrix <- function(x = matrix()) {
22+
inv <- NULL
23+
set <- function(y) {
24+
x <<- y
25+
inv <<- NULL
26+
}
27+
get <- function() x
28+
setinverse <- function(inv) inv <<- inverse
29+
getinverse <- function() inv
30+
list(set = set, get = get,
31+
setinverse = setinverse,
32+
getinverse = getinverse)
33+
}
34+
## Write a short comment describing this function
35+
cacheSolve <- function(x, ...) {
36+
## Return a matrix that is the inverse of 'x'
37+
inv <- x$getinverse()
38+
if(!is.null(inv)) {
39+
message("getting cached data")
40+
return(inv)
41+
}
42+
data <- x$get()
43+
inv <- solve(data, ...)
44+
x$setinverse(inv)
45+
inv
46+
}
47+
exit
48+
;
49+
;;

cachematrix.R

Lines changed: 21 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -4,12 +4,31 @@
44
## Write a short comment describing this function
55

66
makeCacheMatrix <- function(x = matrix()) {
7-
7+
inv <- NULL
8+
set <- function(y) {
9+
x <<- y
10+
inv <<- NULL
11+
}
12+
get <- function() x
13+
setinverse <- function(inv) inv <<- inverse
14+
getinverse <- function() inv
15+
list(set = set, get = get,
16+
setinverse = setinverse,
17+
getinverse = getinverse)
818
}
919

1020

1121
## Write a short comment describing this function
1222

1323
cacheSolve <- function(x, ...) {
1424
## Return a matrix that is the inverse of 'x'
15-
}
25+
inv <- x$getinverse()
26+
if(!is.null(inv)) {
27+
message("getting cached data")
28+
return(inv)
29+
}
30+
data <- x$get()
31+
inv <- solve(data)
32+
x$setinverse(inv)
33+
inv
34+
}

0 commit comments

Comments
 (0)