---
title: R Markdown
author: Rstudio
date: 2021
output:
html_document:
keep_md: yes
pdf_document: default
word_document: default
---
示例如下
a = matrix(1:4,2,2)
a
## [,1] [,2]
## [1,] 1 3
## [2,] 2 4
solve(a) # inverse of a matrix
## [,1] [,2]
## [1,] -2 1.5
## [2,] 1 -0.5
library(MASS)
sa = fractions(solve(a)) # show elements of matrix as fractions
sa
## [,1] [,2]
## [1,] -2 3/2
## [2,] 1 -1/2
根据 Maxim.K 和Blended, 有
m2l <- function(matr) {
printmrow <- function(x) {
ret <- paste(paste(x,collapse = " & "),"\\\\")
ret # sprintf(ret)
}
out <- apply(matr,1,printmrow)
out2 <- paste("\\begin{bmatrix}",paste(out,collapse=' '),"\\end{bmatrix}")
return(out2)
}
write_matex2 <- function(x) {
begin <- "\\begin{bmatrix}"
end <- "\\end{bmatrix}"
X <-
apply(x, 1, function(x) {
paste(
paste(x, collapse = "&"),
"\\\\"
)
})
paste(c(begin, X, end), collapse = "")
}
我们有
$$
A = `r m2l(a)` \Longrightarrow A^{-1} = `r m2l(sa)`
$$
\[A = \begin{bmatrix} 1 & 3 \\ 2 & 4 \\ \end{bmatrix} \Longrightarrow A^{-1} = \begin{bmatrix} -2 & 1.5 \\ 1 & -0.5 \\ \end{bmatrix}\]
$$
A = `r write_matex2(a)` \Longrightarrow A^{-1} = `r write_matex2(sa)`
$$
\[A = \begin{bmatrix}1&3 \\2&4 \\\end{bmatrix} \Longrightarrow A^{-1} = \begin{bmatrix}-2&1.5 \\1&-0.5 \\ \end{bmatrix}\]
但是, 我想得到 (即矩阵元素的小数以分数呈现, 注意到sa = fractions(solve(a))
)
\[A = \begin{bmatrix}1&3 \\2&4 \\\end{bmatrix} \Longrightarrow A^{-1} = \begin{bmatrix}-2&3/2 \\1&-1/2 \\ \end{bmatrix}\]