通过连续步骤将连续行归零,使用高斯-乔丹消除法解决R-Markdown中的方程组

时间:2018-08-17 21:38:54

标签: python r matrix r-markdown

我不太喜欢R。在R-Markdown中,我必须使用Gauss-Jordan消除法来解决随机方程组。重要的是应通过将矩阵中的每一下一行归零来打印下一个矩阵。这意味着对于4 * 5 [A | b]矩阵,应该有4个步骤进行G-J消除-第一步(和第一个矩阵)将第一行归零,第二步第二行,然后像这样继续到最后一行。此外,它还应打印题词“ Step + \连续矩阵编号\”以及正在n行上进行的所有操作。

就像这样(但是需要添加在矩阵上提交的操作):

enter image description here

我使用了第一个答案How to do Gaussian elimination in R (do not use "solve") 现在通过修改它,我只有这个脚本:

```{r setup, include=FALSE, cache=FALSE}
knitr::opts_chunk$set(echo = FALSE, warning=FALSE, comment = "", 
message=FALSE, options(xtable.comment = FALSE))
library(xtable)
```


```{r, results='asis'}

A <- matrix(c(2,-5,4,1,-2.5,1,1,-4,6),byrow=T,nrow=3,ncol=3)
b <- matrix(c(-3,5,10),nrow=3,ncol=1)
p <- nrow(A)
U.pls <- cbind(A,b)

U.pls[1,] <- U.pls[1,]/U.pls[1,1] 
cat("Step..",'\n\n')
cat(noquote(paste0("[w_",1,", ]<-[w_",1,", ]/[w_",1,",k_",1, "]")))
x1=xtable(U.pls,align=rep("",ncol(U.pls)+1)) 
z1<-print(x1, floating=FALSE, tabular.environment="bmatrix", hline.after=NULL, include.rownames=FALSE, include.colnames=FALSE)  

i <- 2
while (i < p+1) {
j <- i
while (j < p+1) {
  U.pls[j, ] <- U.pls[j, ] - U.pls[i-1, ] * U.pls[j, i-1]
  cat("Step..",'\n\n')
  j <- j+1
  cat(noquote(paste0("[w_",j-1,", ]<-[w_",j-1,", ]-([w_",i-1,", ]*[w_",j- 1,",k_",i-1,"])" )))

x2=xtable(U.pls,align=rep("",ncol(U.pls)+1)) 
z2<-print(x2, floating=FALSE, tabular.environment="bmatrix", hline.after=NULL, include.rownames=FALSE, include.colnames=FALSE)      


}
while (U.pls[i,i] == 0) {
  U.pls <- rbind(U.pls[-i,],U.pls[i,])

 x3=xtable(U.pls,align=rep("",ncol(U.pls)+1)) 
 z3<-print(x3, floating=FALSE, tabular.environment="bmatrix", hline.after=NULL, include.rownames=FALSE, include.colnames=FALSE)

}
U.pls[i,] <- U.pls[i,]/U.pls[i,i]
cat("Step..",'\n\n')
cat(noquote(paste0("[w_",i,", ]<-[w_",i,", ]/[w_",i,",k_",i,"])" )))
i <- i+1

x4=xtable(U.pls,align=rep("",ncol(U.pls)+1)) 
z4<-print(x4, floating=FALSE, tabular.environment="bmatrix", hline.after=NULL, include.rownames=FALSE, include.colnames=FALSE)    

}

for (i in p:2) {
    for (j in i:2-1) {
    U.pls[j, ] <- U.pls[j, ] - U.pls[i, ] * U.pls[j, i]
    cat("Step..",'\n\n')
    cat(noquote(paste0("[w_",j,", ]<-[w_",j,", ]-([w_",i,", ]* [w_",j,",k_",i,"])" )))
     x5=xtable(U.pls,align=rep("",ncol(U.pls)+1)) 
     z5<-print(x5, floating=FALSE, tabular.environment="bmatrix", hline.after=NULL, include.rownames=FALSE, include.colnames=FALSE)
    }
}

```

它提供了一个超过10个步骤的解决方案(1个步骤用于1个随机操作) 矩阵)

(...) enter image description here

(...)

需要以这种方式修改(对于特定的方程组)只有3个步骤(3行)。

0 个答案:

没有答案