这是一个矩阵问题,我正在尝试求解满足2个或更多矩阵方程的最佳拟合非负x.我能够单独求解方程式,但我对如何同时求解所有'n'矩阵毫无头绪.
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)
Run Code Online (Sandbox Code Playgroud)
我们假设"最合适"意味着找到x最小化的非负数:
|| A x - c || 2 + || B x - d || 2
我们可以使用nnls包来计算它.假设这mat是由A堆叠在行的顶部的行组成的矩阵B,即rbind(A, B),c并且d它们都是1的向量,因此它c(c, d)是nrow(mat)我们所拥有的向量:
library(nnls)
nnls(mat, rep(1, nrow(mat)))
Run Code Online (Sandbox Code Playgroud)
赠送:
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.
Run Code Online (Sandbox Code Playgroud)