繁体   English   中英

仅当列和行不同时,矩阵向量乘法

[英]Matrix vector multiplication only if column and row are different

我正在实现Jacobi迭代方法来求解线性系统Ax = b

我有以下代码:

data.a <- c(3, -1, 1, 3, 6, 2, 3, 3, 7)
A <- matrix(data.a, nrow = 3, ncol = 3, byrow = TRUE)

b <- c(1, 0, 4)
Xo <- c(0,0,0)
X <- c(0, 0, 0)

 #A is the matrix:
     #3   -1    1
     #3    6    2
     #3    3    7

#b is the column vector:
#[1, 0, 4]

#and Xo is the previous X computed

for(i in 1:nrow(A)){
  sum = 0
  for(j in 1:ncol(A)){
    if(j != i){
      sum = sum + A[i,j]*Xo[j]
    }
  }

  X[i] = -(1/A[i,i])*(sum - b[i])
}

问题是,因为我只乘法和总结值A[i][j]*Xo[j]j != i我使用嵌套的for循环,并使用附配的变量之和。

我的问题是:我可以使用类似

A[i,] %*% Xo

计算没有嵌套循环的总和的值?

编辑:我找到了解决方案

X[i] = -(1/A[i,i])*(A[i,]%*%Xo - A[i,i]*Xo[i] - b[i])
# I subtracted the term A[i,i]*Xo[i] from the product A*Xo

您甚至可以通过制作矩阵R来删除第一个循环,矩阵R的元素等于A,对角线元素为零。

update <- function(x, A, b) {
  D <- diag(diag(A))
  R <- A - D

  sums <- R %*% x
  x <- (b - sums) / diag(D)
  x
}

data.a <- c(3, -1, 1, 3, 6, 2, 3, 3, 7)
A <- matrix(data.a, nrow = 3, ncol = 3, byrow = TRUE)
b <- c(1, 0, 4)

x <- c(0, 0, 0)
for (i in 1:100) x <- update(x, A, b)
x

# verify the answer is correct
solve(A, b)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM