R代码:满足n个矩阵方程

时间:2015-12-25 16:47:52

标签: r math matrix

这是一个矩阵问题,我试图求解满足2个或更多矩阵方程的最佳拟合非负x。我能够单独求解方程式,但我对如何同时求解所有' 矩阵毫无头绪。

  

A x - c = B x - d = E x - f = ... = 0

下面我有两组矩阵,我单独解决。

  

A x = c

     

B y = d

x = y

没有约束
require(pracma)
require(corpcor)
require(NMF)

mat=c(0.005,0.006,0.002,0,0,0,0,
      0,0.005,0.006,0.002,0,0,0,
      0,0,0.005,0.006,0.002,0,0,
      0,0,0,0.005,0.006,0.002,0,
      0,0,0,0,0.005,0.006,0.002,
      0,0,0,0,0,0.005,0.006,
      0.003,0.004,0.002,0,0,0,0,
      0,0.003,0.004,0.002,0,0,0,
      0,0,0.003,0.004,0.002,0,0,
      0,0,0,0.003,0.004,0.002,0,
      0,0,0,0,0.003,0.004,0.002,
      0,0,0,0,0,0.003,0.004     
)
mat = matrix(mat,byrow=T,ncol=7)
rownames(mat) = rep(c("Group A", "Group B"), times = c(6,6))

mat.A = mat[rownames(mat) == "Group A",]
mat.B = mat[rownames(mat) == "Group B",]

y.A = sample(c(100:500), 7)
y.B = sample(c(200:300), 7)

# Solve B
a = t(mat.A)
b = as.numeric(y.A)

Test.a  = qr(a, tol = 0.0000001)
nc = ncol(Test.a$qr)
nr = nrow(Test.a$qr)
if (Test.a$rank != min(nc, nr)){
  x = ceiling(fcnnls(a,b, pseudo = T)$x)
} else x = ceiling(lsqnonneg(a,b)$x)

# Solve A 
a = t(mat.B)
b = as.numeric(y.B)

Test.a  = qr(a, tol = 0.0000001)
nc = ncol(Test.a$qr)
nr = nrow(Test.a$qr)
if (Test.a$rank != min(nc, nr)){
  x = ceiling(fcnnls(a,b, pseudo = T)$x)
} else x = ceiling(lsqnonneg(a,b)$x)

1 个答案:

答案 0 :(得分:8)

我们认为"最适合"意味着找到最小化的非负x

  

|| A x - c || 2 + || B x - d || 2

我们可以使用nnls包来计算它。假设mat是由A的行组成的矩阵组成的行,即B的行,即rbind(A, B),以及c 1}}和d都是1的向量,因此c(c, d)是我们拥有的nrow(mat)个向量:

library(nnls)
nnls(mat, rep(1, nrow(mat)))

,并提供:

Nonnegative least squares model
x estimates: 82.87176 83.51637 104.6671 52.97634 148.3001 0 193.7866 
residual sum-of-squares: 0.39
reason terminated: The solution has been computed sucessfully.