Skip to content

Completed cachematrix.R for Programming Assignment 2 #5797

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
43 changes: 38 additions & 5 deletions cachematrix.R
Original file line number Diff line number Diff line change
@@ -1,15 +1,48 @@
## Put comments here that give an overall description of what your
## functions do
## These functions cache the inverse of a matrix to avoid redundant computations.

## Write a short comment describing this function

## This function creates a special "matrix" object that can cache its inverse.

makeCacheMatrix <- function(x = matrix()) {
inver <- NULL #set inverse as null

set <- function(y) {
x <<- y #set new matrix
inver <<- NULL #reset the inverse
}
get <- function()x #return matrix

setinverse <- function(inverse) inver <<- inverse #cache inverse

getinverse <- function() inver #return cached inverse

list(set = set, get = get,
setinverse = setinverse,
getinverse = getinverse)

}


## Write a short comment describing this function
## computes the inverse of the matrix if not already cached,
## or retrieves it from the cache if it has already been calculated.

cacheSolve <- function(x, ...) {
## Return a matrix that is the inverse of 'x'
inver <- x$getinverse()
if(!is.null(inver)) {
message("getting cached data")
return(inver) #return cached inverse
}
data <- x$get() #set matrix
inver <- solve(data, ...) #solve for inverse
x$setinverse(inver) ## Return a matrix that is the inverse of 'x'
inver
}

##Example matrix

m <- matrix(c(6, 8, 12, 4), nrow = 2, ncol = 2) #create matrix
cache_m <- makeCacheMatrix(m) #create cache matrix
invcache_m <- cacheSolve(cache_m) #get inverse
print(invcache_m)
re_invchache_m<- cacheSolve(cache_m)
print(re_invchache_m)