Skip to content

Commit adc869c

Browse files
author
Andrei Holub
committed
assignment solution
1 parent 7f657dd commit adc869c

File tree

2 files changed

+40
-9
lines changed

2 files changed

+40
-9
lines changed

cachematrix.R

Lines changed: 35 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -1,15 +1,41 @@
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 their may be some
2+
## benefit to caching the inverse of a matrix rather than compute it repeatedly.
3+
## Folowing pair of functions that cache the inverse of a matrix.
54

5+
## The first function, makeCacheMatrix creates a special "matrix", which is
6+
## really a list containing a function to
7+
## 1. set the value of the matrix
8+
## 2. get the value of the matrix
9+
## 3. set the value of the inversed matrix
10+
## 4. get the value of the inversed matrix
611
makeCacheMatrix <- function(x = matrix()) {
7-
12+
s <- NULL
13+
set <- function(y) {
14+
x <<- y
15+
s <<- NULL
16+
}
17+
get <- function() x
18+
setsolve <- function(solve) s <<- solve
19+
getsolve <- function() s
20+
list(set = set, get = get,
21+
setsolve = setsolve,
22+
getsolve = getsolve)
823
}
924

10-
11-
## Write a short comment describing this function
12-
25+
## The following function calculates the inversed matrix of the special "matix"
26+
## created with the above function. However, it first checks to see if the
27+
## inversed matrix has already been calculated. If so, it gets the inversed
28+
## matrix from the cache and skips the computation. Otherwise, it calculates the
29+
## inversed matrix of the data and sets the value of the inversion in the cache
30+
## via the setsolve function.
1331
cacheSolve <- function(x, ...) {
14-
## Return a matrix that is the inverse of 'x'
32+
s <- x$getsolve()
33+
if(!is.null(s)) {
34+
message("getting cached data")
35+
return(s)
36+
}
37+
data <- x$get()
38+
s <- solve(data, ...)
39+
x$setsolve(s)
40+
s
1541
}

test.R

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
source("cachematrix.R")
2+
mat8 <- matrix(1:6, 2)
3+
m <- makeCacheMatrix(mat8[, 2:3])
4+
cacheSolve(m)
5+
cacheSolve(m)

0 commit comments

Comments
 (0)