How to resolve the algorithm Matrix-exponentiation operator step by step in the R programming language

Published on 12 May 2024 09:40 PM
#R

How to resolve the algorithm Matrix-exponentiation operator step by step in the R programming language

Table of Contents

Problem Statement

Most programming languages have a built-in implementation of exponentiation for integers and reals only.

Demonstrate how to implement matrix exponentiation as an operator.

Let's start with the solution:

Step by Step solution about How to resolve the algorithm Matrix-exponentiation operator step by step in the R programming language

Source code in the r programming language

library(Biodem)
m <- matrix(c(3,2,2,1), nrow=2)
mtx.exp(m, 0)
#      [,1] [,2]
# [1,]    1    0
# [2,]    0    1
mtx.exp(m, 1)
#      [,1] [,2]
# [1,]    3    2
# [2,]    2    1
mtx.exp(m, 2)
#      [,1] [,2]
# [1,]   13    8
# [2,]    8    5
mtx.exp(m, 3)
#      [,1] [,2]
# [1,]   55   34
# [2,]   34   21
mtx.exp(m, 10)
#         [,1]   [,2]
# [1,] 1346269 832040
# [2,]  832040 514229

a <- matrix(c(1, 2, 3, 4), 2, 2)
a^1
a^2

`%^%` <- function(mat, n)
{
  is.wholenumber <- function(x, tol = .Machine$double.eps^0.5) abs(x - round(x)) < tol#See the docs for is.integer
  if(is.matrix(mat) && is.numeric(n) && is.wholenumber(n))
  {
    if(n==0) diag(nrow = nrow(mat))#Identity matrix of mat's dimensions
    else if(n == 1) mat
    else if(n > 1) mat %*% (mat %^% (n - 1))
    else stop("Invalid n.")
  }
  else stop("Invalid input type.")
}
#For output:
a %^% 0
a %^% 1
a %^% 2
a %*% a %*% a#Base R's equivalent of a %^% 3
a %^% 3
nonSquareMatrix <- matrix(c(1, 2, 3, 4, 5, 6), nrow = 2, ncol = 3)
nonSquareMatrix %^% 1
nonSquareMatrix %^% 2#R's %*% will throw the error for us

library(Biodem)
`%^%` <- function(mat, n) Biodem::mtx.exp(mat, n)

  

You may also check:How to resolve the algorithm Roots of a function step by step in the Wren programming language
You may also check:How to resolve the algorithm Boolean values step by step in the Trith programming language
You may also check:How to resolve the algorithm Langton's ant step by step in the Processing programming language
You may also check:How to resolve the algorithm Literals/String step by step in the Inform 7 programming language
You may also check:How to resolve the algorithm Happy numbers step by step in the Common Lisp programming language