有效创建三对角矩阵 [英] Efficient creation of tridiagonal matrices

查看:141
本文介绍了有效创建三对角矩阵的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何创建平方带矩阵,在其中给出对角线以及对角线以下和上方的第一个对角线?我正在寻找类似的功能

How can I create a quadratic band matrix, where I give the diagonal and the first diagonal below and above the diagonal? I am looking for a function like

tridiag(upper, lower, main)

其中length(upper)==length(lower)==length(main)-1并返回例如

tridiag(1:3, 2:4, 3:6)

         [,1] [,2] [,3] [,4]
[1,]    3    1    0    0
[2,]    2    4    2    0
[3,]    0    3    5    3
[4,]    0    0    4    6

有一种有效的方法吗?

推荐答案

此函数将执行您想要的操作:

This function will do what you want:

tridiag <- function(upper, lower, main){
    out <- matrix(0,length(main),length(main))
    diag(out) <- main
    indx <- seq.int(length(upper))
    out[cbind(indx+1,indx)] <- lower
    out[cbind(indx,indx+1)] <- upper
    return(out)
}

请注意,当矩阵的索引是2列矩阵时,该索引中的每一行都将被解释为所分配向量中单个值的行索引和列索引.

Note that when the index to a matrix is a 2 column matrix, each row in that index is interpreted as the row and column index for a single value in the vector being assigned.

这篇关于有效创建三对角矩阵的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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