Skip to content

Add files via upload - #5897

Open
manjidarahman4444-arch wants to merge 1 commit into
rdpeng:masterfrom
manjidarahman4444-arch:master
Open

Add files via upload#5897
manjidarahman4444-arch wants to merge 1 commit into
rdpeng:masterfrom
manjidarahman4444-arch:master

Conversation

@manjidarahman4444-arch

Copy link
Copy Markdown

The following pair of functions work together to leverage R's lexical

scoping rules to cache the inverse of a matrix, saving processing power.

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

makeCacheMatrix <- function(x = matrix()) {
## Initialize the inverse property to NULL
inv <- NULL

## Define the function to set a new matrix value
set <- function(y) {
    x <<- y
    inv <<- NULL
}

## Define the function to get the current matrix value
get <- function() {
    x
}

## Define the function to cache the calculated inverse matrix
setInverse <- function(inverse) {
    inv <<- inverse
}

## Define the function to retrieve the cached inverse matrix
getInverse <- function() {
    inv
}

## Return a list of all the defined internal methods
list(set = set, 
     get = get,
     setInverse = setInverse,
     getInverse = getInverse)

}

This function computes the inverse of the special "matrix" returned by

makeCacheMatrix above. If the inverse has already been calculated

(and the matrix has not changed), then cacheSolve retrieves the inverse

directly from the cache environment.

cacheSolve <- function(x, ...) {
## Try to get the inverse from the cache object
inv <- x$getInverse()

## If the cache contains data, return it immediately
if(!is.null(inv)) {
    message("getting cached data")
    return(inv)
}

## If the cache is empty, get the original matrix data
data <- x$get()

## Calculate the inverse using R's built-in solve() function
inv <- solve(data, ...)

## Save the computed inverse matrix back to the cache object
x$setInverse(inv)

## Return the calculated inverse matrix
inv

}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant