用R解欠定线性系统 [英] Solving underdetermined linear systems with R

查看:63
本文介绍了用R解欠定线性系统的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

R 可以解决欠定线性系统:

R can solve underdetermined linear systems:

A = matrix((1:12)^2,3,4,T)
B = 1:3
qr(A)$rank  # 3
qr.solve(A, B)  # solutions will have one zero, not necessarily the same one
# 0.1875 -0.5000  0.3125  0.0000
solve(qr(A, LAPACK = TRUE), B)
# 0.08333333 -0.18750000  0.00000000  0.10416667

(它给出了无穷多个解).

(It gives one solution among the infinity of solutions).

但是,如果排名(此处为2)低于行数(此处为3),则它将行不通:

However, if the rank (here 2) is lower than the number of rows (here 3), it won't work:

A = matrix(c((1:8)^2,0,0,0,0),3,4,T)
B = c(1,2,0)
A
#      [,1] [,2] [,3] [,4]
# [1,]    1    4    9   16
# [2,]   25   36   49   64
# [3,]    0    0    0    0

qr.solve(A, B)  # Error in qr.solve(A, B) : singular matrix
solve(qr(A, LAPACK = TRUE), B)  # Error in qr.coef(a, b) : error code 3 

但是该系统确实有解决方案!

but this system does have a solution!

我知道一般的解决方案是使用SVD或A的广义/伪逆(请参阅

I know that the general solution is to use SVD or generalized/pseudo inverse of A (see this question and its answers), but:

是否存在 solve qr.solve 的平均值,以自动将系统AX = B减少为仅等级(A的等效系统CX = D)行 qr.solve(C,D)可以直接使用吗?

Is there a mean with solve or qr.solve to automatically reduce the system AX=B to an equivalent system CX=D of only rank(A) rows, for which qr.solve(C, D) would simply work out-of-the-box?

示例:

C = matrix(c((1:8)^2),2,4,T)
D = c(1,2)
qr.solve(C, D)
# -0.437500  0.359375  0.000000  0.000000

推荐答案

qr.coef qr 似乎可以完成这项工作:

qr.coef along with qr seem to do the job:

(A <- matrix(c((1:8)^2, 0, 0, 0, 0), nrow = 3, ncol = 4, byrow = TRUE))
#     [,1] [,2] [,3] [,4]
# [1,]    1    4    9   16
# [2,]   25   36   49   64
# [3,]    0    0    0    0
(B <- c(1, 2, 0))
# [1] 1 2 0
(X0 <- qr.coef(qr(A), B))
# [1] -0.437500  0.359375        NA        NA
X0[is.na(X0)] <- 0
X0
# [1] -0.437500  0.359375  0.000000  0.000000
# Verification:
A %*% X0
#      [,1]
# [1,]    1
# [2,]    2
# [3,]    0


第二个例子:


Second example:

(A<-matrix(c(1, 2, 0, 0, 1, 2, 0, 0, 1, 2, 1, 0), nrow = 3, ncol = 4, byrow = TRUE))
#      [,1] [,2] [,3] [,4]
# [1,]    1    2    0    0
# [2,]    1    2    0    0
# [3,]    1    2    1    0
(B<-c(1, 1, 2))
# [1] 1 1 2
qr.solve(A, B)
# Error in qr.solve(A, B) : singular matrix 'a' in solve
(X0 <- qr.coef(qr(A), B))
# [1]  1 NA  1 NA
X0[is.na(X0)] <- 0
X0
# [1] 1 0 1 0
A %*% X0
#      [,1]
# [1,]    1
# [2,]    1
# [3,]    2

这篇关于用R解欠定线性系统的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆