Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Commit 0ca252b

Browse files
committed
submission for Programming Assignement 2
1 parent 7f657dd commit 0ca252b

File tree

1 file changed

+78
-8
lines changed

1 file changed

+78
-8
lines changed

cachematrix.R

Lines changed: 78 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -1,15 +1,85 @@
1-
## Put comments here that give an overall description of what your
2-
## functions do
1+
#
2+
# Matrix inversion is usually a costly computation.
33

4-
## Write a short comment describing this function
4+
# There may be some benefit to caching the inverse of a
5+
# matrix rather than compute it repeatedly. The functions
6+
# below implement a simple way to speed up matrix inversion
7+
# by caching results of previous matrix inversion in memory,
8+
# and retrieving the cached inversion results.
9+
#
10+
## Example
11+
## > x = rbind(c(1, -1/2), c(-1/2, 1))
12+
## > m = makeCacheMatrix(x)
513

6-
makeCacheMatrix <- function(x = matrix()) {
14+
## No cache in the first run
15+
## > cacheSolve(m)
16+
## [,1] [,2]
17+
## [1,] 1.3333333 0.6666667
18+
## [2,] 0.6666667 1.3333333
719

8-
}
920

21+
## Retrieving from the cache in the second run
22+
## > cacheSolve(m)
23+
## getting cached data.
24+
## [,1] [,2]
25+
## [1,] 1.3333333 0.6666667
26+
## [2,] 0.6666667 1.3333333
27+
##
28+
29+
# makeCacheMatrix creates a list containing a function to
30+
# cache the inverse of a matrix in a cache environment
31+
#
32+
# 1. set the value of the matrix
33+
# 2. get the value of the matrix
34+
# 3. set the value of inverse of the matrix
35+
# 4. get the value of inverse of the matrix
36+
#
37+
makeCacheMatrix <- function(x = matrix()) {
38+
inv <- NULL
39+
40+
set <- function(y) {
41+
x <<- y
42+
inv <<- NULL
43+
}
44+
45+
get <- function() x
46+
47+
setinverse <- function(inverse)
48+
{ inv <<- inverse }
49+
50+
getinverse <- function()
51+
{ inv }
52+
53+
list(set=set, get=get,
54+
setinverse=setinverse,
55+
getinverse=getinverse)
56+
}
1057

11-
## Write a short comment describing this function
58+
# cacheSolve(matrix)
59+
#
60+
# The cacheSolve function returns the inverse of the matrix.
61+
# cacheSolve first attempts to get the inverse of the matrix
62+
# from cache (using the getinverse accessor). If the inverse
63+
# exist in memory, then it is returned. If not, cacheSolve
64+
# performs the inversion, caches the result and returns an
65+
# inverted matrix.
66+
#
67+
# This function assumes that the matrix is always invertible.x
68+
#
1269

1370
cacheSolve <- function(x, ...) {
14-
## Return a matrix that is the inverse of 'x'
15-
}
71+
72+
inv <- x$getinverse()
73+
74+
if(!is.null(inv)) {
75+
message("getting cached data.")
76+
return(inv)
77+
}
78+
79+
data <- x$get()
80+
inv <- solve(data)
81+
x$setinverse(inv)
82+
inv
83+
}
84+
85+

0 commit comments

Comments
 (0)