Skip to content

Commit 618e1b9

Browse files
author
Necrum
committed
created makeCacheMatrix() and cacheSolve()
1 parent 7f657dd commit 618e1b9

File tree

1 file changed

+34
-6
lines changed

1 file changed

+34
-6
lines changed

cachematrix.R

Lines changed: 34 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1,15 +1,43 @@
1-
## Put comments here that give an overall description of what your
2-
## functions do
1+
## makeCacheMatrix() creates "matrix" object and
2+
## returns list of functions to manipulate it.
3+
##
4+
## cacheSolve() returns the inverse of a matrix.
5+
## It first checks if the inverse of a matrix has already been calculated,
6+
## otherwise it calculates the inverse of a matrix and puts it to the cache
7+
##
8+
## Example:
9+
## a <- matrix(c(1,2,3,4), nrow=2, ncol=2)
10+
## m <- makeCacheMatrix(a)
11+
## cacheSolve(m)
312

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

6-
makeCacheMatrix <- function(x = matrix()) {
14+
## Creates "matrix" object
715

16+
makeCacheMatrix <- function(x = matrix()) {
17+
x_inverse <- NULL
18+
set <- function(y) {
19+
x <<- y
20+
x_inverse <<- NULL
21+
}
22+
get <- function() x
23+
setinverse <- function(inv) x_inverse <<- inv
24+
getinverse <- function() x_inverse
25+
list(set = set, get = get,
26+
setinverse = setinverse,
27+
getinverse = getinverse)
828
}
929

1030

11-
## Write a short comment describing this function
31+
## Calculates of gets from the cache the inverse of a "matrix" object
1232

1333
cacheSolve <- function(x, ...) {
14-
## Return a matrix that is the inverse of 'x'
34+
inv <- x$getinverse()
35+
if (!is.null(inv)) {
36+
message("getting cached data")
37+
return(inv)
38+
}
39+
data <- x$get()
40+
inv <- solve(data)
41+
x$setinverse(inv)
42+
inv
1543
}

0 commit comments

Comments
 (0)