Skip to content

Commit a1d0caf

Browse files
committedJun 22, 2014
Implement makeCacheMatrix and cacheSolve functions
1 parent 7f657dd commit a1d0caf

File tree

1 file changed

+78
-15
lines changed

1 file changed

+78
-15
lines changed
 

Diff for: ‎cachematrix.R

100644100755
+78-15
Original file line numberDiff line numberDiff line change
@@ -1,15 +1,78 @@
1-
## Put comments here that give an overall description of what your
2-
## functions do
3-
4-
## Write a short comment describing this function
5-
6-
makeCacheMatrix <- function(x = matrix()) {
7-
8-
}
9-
10-
11-
## Write a short comment describing this function
12-
13-
cacheSolve <- function(x, ...) {
14-
## Return a matrix that is the inverse of 'x'
15-
}
1+
## Below functions allows to create a cache-enabled version of matrix and
2+
## cache the matrix' inverse (result of solve function). This allows to cache
3+
## a time consuming operation. For more details refer to functions descriptions.
4+
##
5+
## Usage Example:
6+
## > cm <- makeCacheMatrix(matrix(1:4, ncol=2))
7+
##
8+
## > cm$get()
9+
## [,1] [,2]
10+
## [1,] 1 3
11+
## [2,] 2 4
12+
##
13+
## > cacheSolve(cm)
14+
## [,1] [,2]
15+
## [1,] -2 1.5
16+
## [2,] 1 -0.5
17+
##
18+
## > cacheSolve(cm)
19+
## getting cached data....
20+
## [,1] [,2]
21+
## [1,] -2 1.5
22+
## [2,] 1 -0.5
23+
##
24+
## > cm$getSolve()
25+
## [,1] [,2]
26+
## [1,] -2 1.5
27+
## [2,] 1 -0.5
28+
29+
makeCacheMatrix <- function(x = matrix()) {
30+
# Creates cache-enabled matrix.
31+
#
32+
# Args:
33+
# x: a matrix object
34+
#
35+
# Returns:
36+
# An object with 4 functions:
37+
# - get() returns data
38+
# - set(y) changes data
39+
# - getSolve() returns matrix' inverse
40+
# - setSolve() sets the matrix' inverse
41+
42+
s <- NULL
43+
set <- function(y) {
44+
x <<- y
45+
s <<- NULL
46+
}
47+
get <- function() x
48+
setSolve <- function(solve) s <<- solve
49+
getSolve <- function() s
50+
list(set = set,
51+
get = get,
52+
setSolve = setSolve,
53+
getSolve = getSolve)
54+
}
55+
56+
cacheSolve <- function(x) {
57+
# Caches the inverse of a matrix created with makeCacheMatrix function.
58+
#
59+
# Notes:
60+
# Function doesn't take /.../ argument as /solve/ shouldn't be passed
61+
# more than the data to inverse the matrix.
62+
#
63+
# Args:
64+
# x: matrix created with makeCacheMatrix function.
65+
#
66+
# Returns:
67+
# /x/ matrix' inverse
68+
69+
s <- x$getSolve()
70+
if(!is.null(s)) {
71+
message("getting cached data....")
72+
return(s)
73+
}
74+
data <- x$get()
75+
s <- solve(data)
76+
x$setSolve(s)
77+
s
78+
}

0 commit comments

Comments
 (0)
Please sign in to comment.