Skip to content

Commit 8c2c85b

Browse files
author
Jarno Keskikangas
committed
Solution to programming assigment 2.
1 parent 7f657dd commit 8c2c85b

File tree

1 file changed

+46
-9
lines changed

1 file changed

+46
-9
lines changed

cachematrix.R

Lines changed: 46 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -1,15 +1,52 @@
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 a potentially costly computation.
2+
## makeCacheMatrix creates a matrix with cached inverse attribute
3+
## and cacheSolve efficiently solves matrixes by utilizing cache if inverse
4+
## matrix is already computed.
5+
##
6+
## Functions assume that matrix is invertible.
57

8+
## makeCacheMatrix
9+
##
10+
## Description
11+
## Wraps matrix object to support cache for inverse computation
12+
##
13+
## Parameters
14+
## x Matrix object to be wrapped. Default value: Empty matrix
615
makeCacheMatrix <- function(x = matrix()) {
7-
16+
i <- NULL
17+
get <- function() x
18+
set <- function(y) {
19+
# <<- searches x and y from parent environments instead of defining new variables
20+
x <<- y
21+
i <<- NULL
22+
}
23+
24+
getinverse <- function() i
25+
setinverse <- function(inverse) i <<- inverse
26+
list(set = set, get = get,
27+
setinverse = setinverse, getinverse= getinverse)
828
}
929

10-
11-
## Write a short comment describing this function
12-
30+
## cacheSolve
31+
##
32+
## Description
33+
## Solve matrix using cached result, if available. Otherwise, compute
34+
## inverse using 'solve' function and cache the result.
35+
##
36+
## Parameters
37+
## x cacheMatrix to solve
38+
## ... Extra parameters passed to 'solve' function
1339
cacheSolve <- function(x, ...) {
14-
## Return a matrix that is the inverse of 'x'
40+
i <- x$getinverse()
41+
42+
if(!is.null(i)) {
43+
message("getting cached data")
44+
return(i)
45+
}
46+
47+
data <- x$get()
48+
i <- solve(data, ...)
49+
50+
x$setinverse(i)
51+
i
1552
}

0 commit comments

Comments
 (0)