Sym
objectslibrary(Ryacas0)
Define a character matrix (covariance matrix from a certain \(AR(1)\)):
<- 3
N <- diag(1, 1 + N)
L1 cbind(1+(1:N), 1:N)] <- "-alpha"
L1[<- as.Sym(L1)
L1s L1s
## Yacas matrix:
## [,1] [,2] [,3] [,4]
## [1,] 1 0 0 0
## [2,] -alpha 1 0 0
## [3,] 0 -alpha 1 0
## [4,] 0 0 -alpha 1
Now, this can be converted to a Sym
object:
<- as.Sym(L1)
L1s L1s
## Yacas matrix:
## [,1] [,2] [,3] [,4]
## [1,] 1 0 0 0
## [2,] -alpha 1 0 0
## [3,] 0 -alpha 1 0
## [4,] 0 0 -alpha 1
Operations can be performed:
+ 4 L1s
## Yacas matrix:
## [,1] [,2] [,3] [,4]
## [1,] 5 4 4 4
## [2,] 4 - alpha 5 4 4
## [3,] 4 4 - alpha 5 4
## [4,] 4 4 4 - alpha 5
<- L1s^4
tmp tmp
## Yacas matrix:
## [,1] [,2] [,3]
## [1,] 1 0 0
## [2,] -4 * alpha 1 0
## [3,] 3 * alpha^2 - -3 * alpha^2 -4 * alpha 1
## [4,] -(alpha^3 + alpha * (3 * alpha^2)) 3 * alpha^2 - -3 * alpha^2 -4 * alpha
## [,4]
## [1,] 0
## [2,] 0
## [3,] 0
## [4,] 1
Simplify(tmp)
## Yacas matrix:
## [,1] [,2] [,3] [,4]
## [1,] 1 0 0 0
## [2,] -4 * alpha 1 0 0
## [3,] 6 * alpha^2 -4 * alpha 1 0
## [4,] -4 * alpha^3 6 * alpha^2 -4 * alpha 1
Or the concentration matrix \(K=L L'\) can be found:
<- Simplify(L1s * Transpose(L1s))
K1s K1s
## Yacas matrix:
## [,1] [,2] [,3] [,4]
## [1,] 1 -alpha 0 0
## [2,] -alpha alpha^2 + 1 -alpha 0
## [3,] 0 -alpha alpha^2 + 1 -alpha
## [4,] 0 0 -alpha alpha^2 + 1
This can be converted to \(\LaTeX\):
TeXForm(K1s)
## [1] "\\left( \\begin{array}{cccc} 1 & - \\alpha & 0 & 0 \\\\ - \\alpha & \\alpha ^{2} + 1 & - \\alpha & 0 \\\\ 0 & - \\alpha & \\alpha ^{2} + 1 & - \\alpha \\\\ 0 & 0 & - \\alpha & \\alpha ^{2} + 1 \\end{array} \\right)"
Which look like this:
cat("\\[ K_1 = ", TeXForm(K1s), " \\]", sep = "")
\[ K_1 = \left( \begin{array}{cccc} 1 & - \alpha & 0 & 0 \\ - \alpha & \alpha ^{2} + 1 & - \alpha & 0 \\ 0 & - \alpha & \alpha ^{2} + 1 & - \alpha \\ 0 & 0 & - \alpha & \alpha ^{2} + 1 \end{array} \right) \]
Similar can be done for vectors:
<- paste0("x", 1:2)
x <- as.Sym(x)
xs xs
## Yacas vector:
## [1] x1 x2
And matrix-vector multiplication (or matrix-matrix multiplication):
<- matrix(paste0(paste0("a", 1:2), rep(1:2, each = 2)), 2, 2)
A <- as.Sym(A)
As As
## Yacas matrix:
## [,1] [,2]
## [1,] a11 a12
## [2,] a21 a22
*xs As
## Yacas vector:
## [1] a11 * x1 + a12 * x2 a21 * x1 + a22 * x2
*As As
## Yacas matrix:
## [,1] [,2]
## [1,] a11^2 + a12 * a21 a11 * a12 + a12 * a22
## [2,] a21 * a11 + a22 * a21 a21 * a12 + a22^2
xs
## Yacas vector:
## [1] x1 x2
Eval(xs, list(x1 = 2, x2 = 3))
## [1] 2 3
As
## Yacas matrix:
## [,1] [,2]
## [1,] a11 a12
## [2,] a21 a22
Eval(As, list(a11 = 11, a12 = 12, a21 = 21, a22 = 22))
## [,1] [,2]
## [1,] 11 12
## [2,] 21 22
The functionality can be disabled as follows:
Ryacas_options("module_matvec_enabled")
## [1] TRUE
As
## Yacas matrix:
## [,1] [,2]
## [1,] a11 a12
## [2,] a21 a22
Ryacas_options(module_matvec_enabled = FALSE)
As
## yacas_expression(list(list(a11, a12), list(a21, a22)))