From dbb6885c82a169de8362f46cf7d262f7bdc22c6d Mon Sep 17 00:00:00 2001 From: baoanh1809-byte Date: Tue, 23 Jun 2026 21:14:17 +0700 Subject: [PATCH 1/3] Add files via upload --- cachematrix.R | 57 +++++++++++++++++++++++++++++++++++++-------------- 1 file changed, 42 insertions(+), 15 deletions(-) diff --git a/cachematrix.R b/cachematrix.R index a50be65aa44..9b656caf3ad 100644 --- a/cachematrix.R +++ b/cachematrix.R @@ -1,15 +1,42 @@ -## Put comments here that give an overall description of what your -## functions do - -## Write a short comment describing this function - -makeCacheMatrix <- function(x = matrix()) { - -} - - -## Write a short comment describing this function - -cacheSolve <- function(x, ...) { - ## Return a matrix that is the inverse of 'x' -} +makeCacheMatrix <- function(x = matrix()) { + inv <- NULL + + set <- function(y) { + x <<- y + inv <<- NULL + } + + get <- function() x + + setinverse <- function(inverse) { + inv <<- inverse + } + + getinverse <- function() { + inv + } + + list( + set = set, + get = get, + setinverse = setinverse, + getinverse = getinverse + ) +} + + +cacheSolve <- function(x, ...) { + inv <- x$getinverse() + + if(!is.null(inv)) { + message("getting cached data") + return(inv) + } + + data <- x$get() + inv <- solve(data, ...) + + x$setinverse(inv) + + inv +} From 654745cb1a360c33a64826bb0b599e5980672a5b Mon Sep 17 00:00:00 2001 From: baoanh1809-byte Date: Tue, 23 Jun 2026 21:20:00 +0700 Subject: [PATCH 2/3] Add files via upload From 0e3fd2825a38682687f88f5f3ad2619e083aa3e1 Mon Sep 17 00:00:00 2001 From: baoanh1809-byte Date: Fri, 26 Jun 2026 18:51:18 +0700 Subject: [PATCH 3/3] cachematrix.R --- cachematrix.R | 29 +++++++++++++++++++---------- 1 file changed, 19 insertions(+), 10 deletions(-) diff --git a/cachematrix.R b/cachematrix.R index 9b656caf3ad..a33ecdf382c 100644 --- a/cachematrix.R +++ b/cachematrix.R @@ -1,21 +1,28 @@ +## These functions cache the inverse of a matrix so that the inverse +## is computed only once. If the inverse has already been calculated, +## the cached value is returned instead of recomputing it. + +## Create a special matrix object that can store a matrix and cache +## its inverse. + makeCacheMatrix <- function(x = matrix()) { inv <- NULL - + set <- function(y) { x <<- y inv <<- NULL } - + get <- function() x - + setinverse <- function(inverse) { inv <<- inverse } - + getinverse <- function() { inv } - + list( set = set, get = get, @@ -24,19 +31,21 @@ makeCacheMatrix <- function(x = matrix()) { ) } +## Return the cached inverse if available; otherwise compute the +## inverse, cache it, and return it. cacheSolve <- function(x, ...) { inv <- x$getinverse() - - if(!is.null(inv)) { + + if (!is.null(inv)) { message("getting cached data") return(inv) } - + data <- x$get() inv <- solve(data, ...) - + x$setinverse(inv) - + inv }