Skip to content

Commit 20e3736

Browse files
Do assignment -- added tests
1 parent 7f657dd commit 20e3736

File tree

2 files changed

+65
-7
lines changed

2 files changed

+65
-7
lines changed

cachematrix.R

Lines changed: 36 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -1,15 +1,44 @@
11
## Put comments here that give an overall description of what your
22
## functions do
33

4-
## Write a short comment describing this function
5-
4+
# Returns a container that can hold a matrix, and some cached data computed
5+
# from the matrix
66
makeCacheMatrix <- function(x = matrix()) {
7-
7+
cached.transposed <- NULL
8+
9+
# Update matrices
10+
set <- function(y) {
11+
x <<- y
12+
cached.transposed <<- NULL
13+
}
14+
get <- function() x
15+
16+
# Transposed
17+
set.cached.transposed <- function(transposed) {
18+
cached.transposed <<- transposed
19+
}
20+
get.cached.transposed <- function() cached.transposed
21+
22+
list(set = set,
23+
get = get,
24+
set.cached.transposed = set.cached.transposed,
25+
get.cached.transposed = get.cached.transposed)
26+
827
}
928

1029

11-
## Write a short comment describing this function
12-
30+
## Returns a transposed version of the matrix contained in x
31+
#
32+
# This function returns a transposed version of the matrix that is
33+
# stored in x, and will cache it for subsequent calls
1334
cacheSolve <- function(x, ...) {
14-
## Return a matrix that is the inverse of 'x'
15-
}
35+
transposed <- x$get.cached.transposed()
36+
if (!is.null(transposed)) {
37+
message("returning cached transposed matrix")
38+
return(transposed)
39+
}
40+
41+
transposed <- t(x$get(), ...)
42+
x$set.cached.transposed(transposed)
43+
transposed
44+
}

tests.R

Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
source("cachematrix.R")
2+
3+
assert.cached <- function(m, v) stopifnot(identical(m$get.cached.transposed(), v))
4+
assert.uncached <- function(m) assert.cached(m, NULL)
5+
6+
# test with null matrix
7+
m <- makeCacheMatrix(x = matrix())
8+
9+
stopifnot(identical(m$get(), matrix()))
10+
assert.uncached(m)
11+
12+
stopifnot(identical(cacheSolve(m), matrix()))
13+
assert.cached(m, matrix())
14+
stopifnot(identical(m$get(), matrix()))
15+
16+
# Test with actual matrix
17+
mat <- matrix(c(1, 2, 3, 4), 2, 2)
18+
m <- makeCacheMatrix(mat)
19+
stopifnot(identical(m$get(), mat))
20+
assert.uncached(m)
21+
stopifnot(identical(cacheSolve(m), t(mat)))
22+
stopifnot(identical(m$get(), mat))
23+
assert.cached(m, t(mat))
24+
25+
# Ensure calling set() resets the cache
26+
mat <- matrix(c(1, 2, 3, 4), 4, 1)
27+
m$set(mat)
28+
stopifnot(identical(m$get(), mat))
29+
assert.uncached(m)

0 commit comments

Comments
 (0)