From 7ee27d01a1e498f5486c8b6cac16dfb976534688 Mon Sep 17 00:00:00 2001 From: aluminumpotato <128320077+aluminumpotato@users.noreply.github.com> Date: Sun, 25 May 2025 18:55:29 -0400 Subject: [PATCH] Completed cachematrix.R for Programming Assignment 2 --- cachematrix.R | 43 ++++++++++++++++++++++++++++++++++++++----- 1 file changed, 38 insertions(+), 5 deletions(-) diff --git a/cachematrix.R b/cachematrix.R index a50be65aa44..71a77cfacbf 100644 --- a/cachematrix.R +++ b/cachematrix.R @@ -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) \ No newline at end of file