Skip to content

Commit 8a156aa

Browse files
committed
+ makeCacheMatrix and cacheSolve
1 parent 7f657dd commit 8a156aa

File tree

3 files changed

+53
-8
lines changed

3 files changed

+53
-8
lines changed

cachematrix.R

Lines changed: 28 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -1,15 +1,35 @@
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+
## Matrix inversion is usually a costly computation and there may be some
2+
## benefit to caching the inverse of a matrix rather than compute it repeatedly.
3+
##
4+
## makeCacheMatrix creates a matrix that can cache its inverse.
5+
##
6+
## cacheSolve returns inverse of the matrix created by makeCacheMatrix,
7+
## caching result for possible future calls.
8+
##
59

10+
## Creates a special "matrix" object that can cache its inverse.
611
makeCacheMatrix <- function(x = matrix()) {
7-
12+
m <- NULL
13+
set <- function(y) {
14+
x <<- y
15+
m <<- NULL
16+
}
17+
get <- function() x
18+
setsolve <- function(solve) m <- solve
19+
getsolve <- function() m
20+
list(set=set, get=get, setsolve=setsolve, getsolve=getsolve)
821
}
922

1023

11-
## Write a short comment describing this function
12-
24+
## Returns a matrix that is the inverse of 'x'
1325
cacheSolve <- function(x, ...) {
14-
## Return a matrix that is the inverse of 'x'
26+
m <- x$getsolve()
27+
if(!is.null(m)) {
28+
message("getting cached data")
29+
return(m)
30+
}
31+
data <- x$get()
32+
m <- solve(data, ...)
33+
x$setsolve(m)
34+
m
1535
}

run_tests.R

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,7 @@
1+
library("RUnit")
2+
source("cachematrix.R")
3+
4+
test.suite <- defineTestSuite('cachematrix', file.path('.'))
5+
test.result <- runTestSuite(test.suite)
6+
7+
printTextProtocol(test.result)

runit.cachematrix.R

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,18 @@
1+
2+
test.makeCacheMatrix <- function() {
3+
m <- matrix( sample(rnorm(1000), 16), 4,4)
4+
x <- makeCacheMatrix(m)
5+
checkTrue(is.list(x))
6+
checkTrue(is.function(x$set))
7+
checkTrue(is.function(x$get))
8+
checkTrue(is.function(x$setsolve))
9+
checkTrue(is.function(x$getsolve))
10+
}
11+
12+
13+
test.cacheSolve <- function() {
14+
m <- matrix( sample(rnorm(1000), 16), 4,4)
15+
x <- makeCacheMatrix(m)
16+
r <- cacheSolve(x)
17+
checkIdentical(r, solve(m))
18+
}

0 commit comments

Comments
 (0)