calc_invrec: Calculate the approximate inverse of a square _matrix_...

View source: R/RcppExports.R

calc_invrecR Documentation

Calculate the approximate inverse of a square matrix recursively using the Schulz formula (without copying the data in memory).

Description

Calculate the approximate inverse of a square matrix recursively using the Schulz formula (without copying the data in memory).

Usage

calc_invrec(matrixv, invmat, niter = 1L)

Arguments

matrixv

A matrix of data to be inverted.

invmat

A matrix of data equal to the starting point for the recursion.

niter

An integer equal to the number of recursion iterations.

Details

The function calc_invrec() calculates the approximate inverse \strong{A}^{-1} of a square matrix \strong{A} recursively using the Schulz formula:

\strong{A}_{i+1}^{-1} \leftarrow 2 \strong{A}_i^{-1} - \strong{A}_i^{-1} \strong{A} \strong{A}_i^{-1}

The Schulz formula is repeated niter times. The Schulz formula is useful for updating the inverse when the matrix \strong{A} changes only slightly. For example, for updating the inverse of the covariance matrix as it changes slowly over time.

The function calc_invrec() accepts a pointer to the argument invmat (which is the initial value of the inverse matrix for the recursion), and it overwrites the old inverse matrix values with the updated inverse values.

The function calc_invrec() performs the calculation in place, without copying the matrix in memory, which can significantly increase the computation speed for large matrices.

The function calc_invrec() doesn't return a value. The function calc_invrec() performs the calculations using C++ Armadillo code.

Value

No return value.

Examples

## Not run: 
# Calculate a random matrix
matrixv <- matrix(rnorm(100), nc=10)
# Define the initial value of the inverse matrix
invmat <- solve(matrixv) + matrix(rnorm(100, sd=0.1), nc=10)
# Calculate the inverse in place using RcppArmadillo
HighFreq::calc_invrec(matrixv, invmat, 3)
# Multiply the matrix times its inverse
multmat <- matrixv %*% invmat
round(multmat, 4)
# Calculate the sum of the off-diagonal elements
sum(multmat[upper.tri(multmat)])
# Compare RcppArmadillo with R
all.equal(invmat, solve(matrixv))
# Compare the speed of RcppArmadillo with R code
library(microbenchmark)
summary(microbenchmark(
   rcode=solve(matrixv),
   cppcode=HighFreq::calc_invrec(matrixv, invmat, 3),
   times=10))[, c(1, 4, 5)]

## End(Not run)


algoquant/HighFreq documentation built on Feb. 9, 2024, 8:15 p.m.