Skip to content

Update cachematrix.R #5802

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 2 commits into
base: master
Choose a base branch
from
Open
Changes from 1 commit
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
60 changes: 32 additions & 28 deletions cachematrix.R
Original file line number Diff line number Diff line change
Expand Up @@ -6,38 +6,42 @@
## This function computes the median of the special "matrix" returned by makeCacheMatrix.

makeCacheMatrix <- function(x = matrix()) {
m <- NULL

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

instead of mean , calculate inverse

set <- function(y) {
x <<- y
m <<- NULL
}
get <- function() x
setmedian <- function(median) m <<- median

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

setInverse<-function() inv<<-solve(x)

getmedian <- function() m
list(set = set, get = get,
setmedian = setmedian,
getmedian = getmedian)

inv <- NULL

set <- function(y) {
x <<- y
inv <<- NULL # Reset the inverse when the matrix is changed
}

get <- function() x

setInverse <- function(inverse) inv <<- inverse

getInverse <- function() inv

list(set = set,
get = get,
setInverse = setInverse,
getInverse = getInverse)
}




## If the median has already been calculated (and the matrix has not changed),
## then it retrieves the median from the cache.



cacheMedian <- function(x, ...) {
m <- x$getmedian()
if(!is.null(m)) {
message("getting cached data")
return(m)
}
data <- x$get()
m <- median(data, ...)
x$setmedian(m)
m
}
cacheSolve <- function(x, ...) {
  # Try to get the cached inverse
  inv <- x$getInverse()

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

  # If not cached, compute the inverse
  mat <- x$get()         # Get the matrix
  inv <- solve(mat, ...) # Compute the inverse using solve()

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

calculate inverse


  # Cache the inverse for future use