我需要在R中求解一个线性方程组 - 我能够做得很好。请参阅以下代码:
A<-matrix(c(1:5,2,1,2:4,3,2,1:3,4:2,1,2,5:1),nrow=5) #Creates a matrix of the coefficients
A #Displays the matrix of coefficients (below)
[,1] [,2] [,3] [,4] [,5]
[1,] 1 2 3 4 5
[2,] 2 1 2 3 4
[3,] 3 2 1 2 3
[4,] 4 3 2 1 2
[5,] 5 4 3 2 1
kv<-matrix(c(7,-1,-3,5,17),nrow=5) #Creates a column vector of the known values
kv #Displays the column vector
[,1]
[1,] 7
[2,] -1
[3,] -3
[4,] 5
[5,] 17
solve(A,kv) #Solves the continuous equation
[,1]
[1,] -2
[2,] 3
[3,] 5
[4,] 2
[5,] -4
问题是我现在需要概括我的解决方案,它可以用于具有相同结构但尺寸更大的方程组 - 没有像我上面那样键入矩阵A的所有值。
是否有人能够指出我如何处理系数矩阵的正确方向,但是程序可以用来解决其他系统?
感谢任何帮助 感谢
答案 0 :(得分:0)
如果我理解正确:
bandmat <- function(n){
require(Matrix)
as.matrix(bandSparse(n,n,-(n-1):(n-1),diag=lapply(c(n:1,2:n),function(i) rep(i,n))))
}
bandmat(4)
[,1] [,2] [,3] [,4]
[1,] 1 2 3 4
[2,] 2 1 2 3
[3,] 3 2 1 2
[4,] 4 3 2 1
可能有一种更方便的方法来构建它。
编辑: 这是你如何使用它。
#create some vector
set.seed(42)
kv <- sample(-10:10,10)
#[1] 9 8 -5 4 0 -2 1 -9 5 2
#solve equation system
solve(bandmat(length(kv)),kv)
#[1] 0.0 -6.0 11.0 -6.5 1.0 2.5 -6.5 12.0 -8.5 2.0