Skip to content

Commit 95db61f

Browse files
committed
Programming Assignment 2: Lexical Scoping
2014.07.27 rdpeng#1 Committing "Programming Assignment 2: Lexical Scoping" R file into my git repository
1 parent 7f657dd commit 95db61f

File tree

1 file changed

+44
-6
lines changed

1 file changed

+44
-6
lines changed

cachematrix.R

Lines changed: 44 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1,15 +1,53 @@
1-
## Put comments here that give an overall description of what your
2-
## functions do
1+
## Below are two functions that are used to create a special object
2+
## that stores a matrix and cache's its inverse.
3+
## (We assume that the matrix supplied is always invertible.)
34

4-
## Write a short comment describing this function
55

6-
makeCacheMatrix <- function(x = matrix()) {
6+
## The first function creates a special "matrix" object that can cache its inverse.
7+
## Example:
8+
## For the sake of fun, run the following in your R console:
9+
## > rpeng <- makeCacheMatrix(matrix(1:4, 2, 2))
10+
## (This is an example. You can change "rpeng" or the content of the square matrix as you wish!)
11+
## Till now, the inverse has not been calculated. To make sure, you can run the following:
12+
## > rpeng$getSolve()
13+
## As you see, you get a matrix with NA values.
714

15+
makeCacheMatrix <- function(x = matrix()) {
16+
s <- matrix(NA, nrow(x), nrow(x))
17+
set <- function(y) {
18+
x <<- y
19+
s <<- matrix(NA, nrow(x), nrow(x))
20+
}
21+
get <- function() x
22+
setSolve <- function(solve) s <<- solve
23+
getSolve <- function() s
24+
list(set = set, get = get,
25+
setSolve = setSolve,
26+
getSolve = getSolve)
827
}
928

1029

11-
## Write a short comment describing this function
30+
## The second function computes the inverse of the special "matrix" returned by makeCacheMatrix above.
31+
## If the inverse has already been calculated (and the matrix has not changed),
32+
## then the cachesolve should retrieve the inverse from the cache
33+
34+
## Example (Continued):
35+
## Run the following:
36+
## > cacheSolve(rpeng)
37+
## You will see the inverse.
38+
## If you run the above command again (it means that you have not changed the matrix),
39+
## you will see this message: "getting cached data" and the cached inverse matrix.
1240

1341
cacheSolve <- function(x, ...) {
1442
## Return a matrix that is the inverse of 'x'
15-
}
43+
s <- x$getSolve()
44+
if(!anyNA(s)) {
45+
message("getting cached data")
46+
return(s)
47+
invisible(x)
48+
}
49+
data <- x$get()
50+
s <- solve(data, ...)
51+
x$setSolve(s)
52+
s
53+
}

0 commit comments

Comments
 (0)