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

Skip to content

Commit a32e4a3

Browse files
author
Richard Shaw
committed
Creation of...
makeCacheMatrix: This function creates a special "matrix" object that can cache its inverse. cacheSolve: This function computes the inverse of the special "matrix" returned by makeCacheMatrix above.
1 parent 7f657dd commit a32e4a3

File tree

1 file changed

+54
-7
lines changed

1 file changed

+54
-7
lines changed

cachematrix.R

Lines changed: 54 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -1,15 +1,62 @@
11
## Put comments here that give an overall description of what your
22
## functions do
33

4-
## Write a short comment describing this function
5-
4+
## makeCacheMatrix creates a special "matrix", which is really a list containing a function which
5+
## 0. Checks we have a square matrix
6+
## 1. set the value of the matrix
7+
## 2. get the value of the matrix
8+
## 3. set the value of the matrix inverse
9+
## 4. get the value of the matrix inverse
610
makeCacheMatrix <- function(x = matrix()) {
7-
11+
12+
## Validation you can only inverse a square matrix using solve()
13+
## Check we have a square matrix
14+
if(nrow(x) != ncol(x)) {
15+
stop('Matrix isn\'t square. Inverse can only be calculated on square matrix')
16+
}
17+
18+
#On creation initalize value of inverse var
19+
i <- NULL
20+
## Save matrix data in object
21+
## Clears any previously calculated inverse
22+
set <- function(y) {
23+
x <<- y
24+
i <<- NULL
25+
}
26+
## Returns cached matrix data
27+
get <- function() x
28+
## Cache inverse of matrix
29+
setInverse <- function(inverse) i <<- inverse
30+
## Return cache inverse of matrix
31+
getInverse <- function() i
32+
33+
list(set = set, get = get,
34+
setInverse = setInverse,
35+
getInverse = getInverse)
36+
837
}
938

10-
11-
## Write a short comment describing this function
12-
39+
## Function calculates the inverse of the special "matrix" created with the makeCacheMatrix function.
40+
## 'x' is a makeCacheMatrix object
41+
## It first checks to see if the inverse has already been calculated.
42+
## If it has gets it the inverse from the cache and skips the computation.
43+
## Otherwise, it calculates the inverse of 'x'
44+
## and sets the value of the inverse matrix in the cache using the setinverse function.
1345
cacheSolve <- function(x, ...) {
14-
## Return a matrix that is the inverse of 'x'
46+
## Looks for inverse in cache
47+
i <- x$getInverse()
48+
if(!is.null(i)) {
49+
message("getting cached data")
50+
## Inverse is not null so return value
51+
return(i)
52+
}
53+
## Inverse is not availble so calculate
54+
## Get matrix data from the makeCacheMatrix object
55+
data <- x$get()
56+
## Calculate inverse of data
57+
i <- solve(data, ...)
58+
## Cache inverse in object
59+
x$setInverse(i)
60+
## Return inverse of matrix
61+
i
1562
}

0 commit comments

Comments
 (0)