Skip to content

Commit c8df9f9

Browse files
committed
submitting assignment
1 parent 06d8113 commit c8df9f9

File tree

2 files changed

+59
-8
lines changed

2 files changed

+59
-8
lines changed

ProgrammingAssignment2

Lines changed: 0 additions & 1 deletion
This file was deleted.

cachematrix.R

Lines changed: 59 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -1,15 +1,67 @@
1-
## Put comments here that give an overall description of what your
2-
## functions do
1+
## makeCacheMatrix and cacheSolve are used to create an object-like list
2+
## for a square invertible matrix and then solve for the inverse of that matrix.
3+
## The inverse is cached for later use to speed up program execution.
34

4-
## Write a short comment describing this function
5+
## The makeCacheMatrix function takes a matrix as input and returns a list of
6+
## functions to:
7+
## 1. set the value of the matrix
8+
## 2. get the value of the matrix
9+
## 3. set the value of the inverse of the matrix (and cache the value)
10+
## 4. get the value of the inverse of the matrix
11+
## Note: The matrix is assumed to be a square invertible matrix.
512

613
makeCacheMatrix <- function(x = matrix()) {
7-
14+
m <- NULL
15+
set <- function(y) {
16+
x <<- y
17+
m <<- NULL
18+
}
19+
get <- function() x
20+
setinverse <- function(inverse) m <<- inverse
21+
getinverse <- function() m
22+
list(set = set, get = get,
23+
setinverse = setinverse,
24+
getinverse = getinverse)
825
}
926

10-
11-
## Write a short comment describing this function
27+
## The cacheSolve function calculates the inverse of a "makeCacheMatrix" matrix
28+
## as created above. If this value has already been cached, cacheSolve simply
29+
## returns the value without having to do any further resource draining calculations.
1230

1331
cacheSolve <- function(x, ...) {
14-
## Return a matrix that is the inverse of 'x'
32+
## Return a matrix that is the inverse of 'x'
33+
m <- x$getinverse()
34+
if(!is.null(m)) {
35+
message("getting cached data")
36+
return(m)
37+
}
38+
data <- x$get()
39+
m <- solve(data, ...)
40+
x$setinverse(m)
41+
m
1542
}
43+
44+
## Below is just some example code that can be used to test the above functions.
45+
46+
#test <- matrix(rnorm(9), 3, 3)
47+
#test
48+
#expected <- solve(test)
49+
50+
#cachetest <- makeCacheMatrix(test)
51+
#cachesolvetest <- cacheSolve(cachetest)
52+
53+
#cachesolvetest == expected
54+
55+
#cachesolvetest <- cacheSolve(cachetest)
56+
57+
## This output shows that the cached value is properly retrieved:
58+
## > cachesolvetest2 <- cacheSolve(cachetest)
59+
## getting cached data
60+
61+
#cachesolvetest == cachesolvetest2 & cachesolvetest2 == expected
62+
63+
## All the calculated inverses are logically equivalent as expected:
64+
## [,1] [,2] [,3]
65+
## [1,] TRUE TRUE TRUE
66+
## [2,] TRUE TRUE TRUE
67+
## [3,] TRUE TRUE TRUE

0 commit comments

Comments
 (0)