Skip to content
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

Completed programming assignment 2Completed programming assignment 2 #5749

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
50 changes: 40 additions & 10 deletions cachematrix.R
Original file line number Diff line number Diff line change
@@ -1,15 +1,45 @@
## Put comments here that give an overall description of what your
## functions do

## Write a short comment describing this function

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

inv <- NULL # Initialize inverse as NULL

# Function to set the value of the matrix
set <- function(y) {
x <<- y
inv <<- NULL # Reset inverse when the matrix changes
}

# Function to get the value of the matrix
get <- function() x

# Function to set the inverse of the matrix
setinverse <- function(inverse) inv <<- inverse

# Function to get the inverse of the matrix
getinverse <- function() inv

# Return a list of functions
list(set = set, get = get, setinverse = setinverse, getinverse = getinverse)
}


## Write a short comment describing this function

# This function computes the inverse of the special matrix returned by makeCacheMatrix
cacheSolve <- function(x, ...) {
## Return a matrix that is the inverse of 'x'
inv <- x$getinverse() # Check if inverse is already cached

# If inverse is cached, return it
if (!is.null(inv)) {
message("Getting cached inverse")
return(inv)
}

# Otherwise, compute the inverse
data <- x$get()
inv <- solve(data, ...) # Compute the inverse using solve()
x$setinverse(inv) # Cache the computed inverse
inv # Return the inverse
}

# Example usage:
# matrix_data <- matrix(c(1, 2, 3, 4), 2, 2)
# special_matrix <- makeCacheMatrix(matrix_data)
# cacheSolve(special_matrix) # Computes and caches inverse
# cacheSolve(special_matrix) # Retrieves cached inverse