Skip to content

Commit 051670c

Browse files
committed
Completed both makeCacheMatrix and makeSolve functions
1 parent 7f657dd commit 051670c

File tree

1 file changed

+49
-6
lines changed

1 file changed

+49
-6
lines changed

cachematrix.R

Lines changed: 49 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1,15 +1,58 @@
1-
## Put comments here that give an overall description of what your
2-
## functions do
1+
## makeCacheMatrix function creates a matrix object out of a matrix 'x' that
2+
## contains getters and setters functions for the value of the matrix and also
3+
## the inverse of the matrix.
4+
## cacheSolve is a function that takes the matrix object created by makeCacheMatrix
5+
## function and tries to calculate the inverse of the matrix object if the inverse
6+
## of the object is not calculated before and cached.
37

4-
## Write a short comment describing this function
8+
## Creates an a matrix, x, which is the input argument. Function has methods
9+
## that returns the inverse of matrix, x. The function contains is a list of
10+
## functions:
11+
## 1. set the matrix
12+
## 2. get the matrix
13+
## 3. set the inverse of the matrix
14+
## 4. get the inverse of the matrix
515

616
makeCacheMatrix <- function(x = matrix()) {
7-
17+
##variable that caches the inverse of matrix x
18+
inv <- NULL
19+
## Set the matrix and resets the cached inverse matrix to NULL
20+
set <- function(y = matrix()){
21+
x <<- y
22+
inv <<- NULL
23+
}
24+
## Returns the matrix
25+
get <- function() x
26+
## Sets the inverse of the matrix in variable inv
27+
setinv <- function(solve) inv <<- solve
28+
## Gets the inverse of the matrix
29+
getinv <-function() inv
30+
## List of functions in this function
31+
list(set = set, get = get,
32+
setinv = setinv,
33+
getinv = getinv)
834
}
935

1036

11-
## Write a short comment describing this function
37+
## Functions returns the inverse of a matrix 'x' by first attempting to return
38+
## any non-null inverse matrix value that is cached. If the inverse matrix value
39+
## is not cached, the inverse of matrix 'x' is calculated and cached before
40+
## the value of the inverse matrix is return.
1241

1342
cacheSolve <- function(x, ...) {
14-
## Return a matrix that is the inverse of 'x'
43+
## Gets the inverse from the matrix object
44+
inv <- x$getinv()
45+
## if the inverse is cached, return the cached inverse matrix
46+
if(!is.null(inv)){
47+
message("getting cached data")
48+
return(inv)
49+
}
50+
## get the matrix data
51+
data <- x$get()
52+
## Calculate the inverse of the matrix 'x'
53+
inv <- solve(data, ...)
54+
## cache the inverse value of matrix 'x'
55+
x$setinv(inv)
56+
## Return a matrix that is the inverse of 'x'
57+
inv
1558
}

0 commit comments

Comments
 (0)