Skip to content

Commit

Permalink
Update cachematrix.R
Browse files Browse the repository at this point in the history
Test criteria:
1) matrixObj <- makeCacheMatrix(matrix(1:4, 2, 2))
2) matrixObj$getInverse()  ## Returns NULL since matrix has not been solved yet
3) cacheSolve(matrixObj) ## Solves and returns matrix object
4) cacheSolve(matrixObj) rdpeng#3 Retruns matrix object from cache
5) matrixObj <- makeCacheMatrix(matrix(1:9, 3, 3))
6) cacheSolve(matrixObj) ## Returns message: Matrix is singular and cannot be inversed and stops
  • Loading branch information
arsubram authored May 21, 2017
1 parent 7f657dd commit ebde259
Showing 1 changed file with 52 additions and 8 deletions.
60 changes: 52 additions & 8 deletions cachematrix.R
Original file line number Diff line number Diff line change
@@ -1,15 +1,59 @@
## Put comments here that give an overall description of what your
## functions do

## Write a short comment describing this function
## Caching the Inverse of a Matrix:
## Matrix inversion is usually a costly computation and there may be some
## benefit to caching the inverse of a matrix rather than compute it repeatedly.
## Below are a pair of functions that are used to create a special object that
## stores a matrix and caches its inverse.

## This function creates a special "matrix" object that can cache its inverse
makeCacheMatrix <- function(x = matrix()) {

m <- NULL
set <- function(y) {
x <<- y
m <<- NULL
}
get <- function() x
setInverse <- function(inverse) m <<- inverse
getInverse <- function() m
list(set = set,
get = get,
setInverse = setInverse,
getInverse = getInverse)


}


## Write a short comment describing this function

## This function returns a matrix that is the inverse of argument 'x'
## Returns from cache if exists already otherwise calls makeCacheMatrix
cacheSolve <- function(x, ...) {
## Return a matrix that is the inverse of 'x'

m <- x$getInverse()
if(!is.null(m)) {
message("getting cached data")
return(m)
}

# Data was not found in the cache above...solve it

data <- x$get()

# Check if matrix can be inversed. Singular matrixes
# cannot be inversed. No point in proceeding otherwise.

f <- function(j) class(try(solve(j),silent=T))=="matrix"

if(f(data)) {
m <- solve(data, ...)
x$setInverse(m)
m
}
else
{
# Provide a meaningful error and bail out
message("Matrix is singular and cannot be inversed")
stop("Retry with different data")
}



}

0 comments on commit ebde259

Please sign in to comment.