gpt4 book ai didi

matrix - 如何在 Julia 中以对角线形式连接矩阵

转载 作者:行者123 更新时间:2023-12-04 02:26:04 29 4
gpt4 key购买 nike

我有一个矩阵 A我想建立一个块对角矩阵 M作为

A 0 ⋯ 0
0 A ⋯ 0
⋮ ⋮ ⋱ ⋮
0 0 ⋯ A
哪里 0 s 是与 A 大小相同的矩阵充满零。有没有方便的方法来做到这一点?
换句话说,是否有等效于 Python 的 linalg.block_diag (来自 scipy)?

最佳答案

您可以使用 blockdiag来自 SparseArrays.jl 标准库。例如:

julia> using SparseArrays

julia> A = sparse(rand(3,2)) # A must be sparse for blockdiag
3×2 SparseMatrixCSC{Float64, Int64} with 6 stored entries:
0.465226 0.473656
0.230678 0.391924
0.928409 0.772551

julia> M = blockdiag(A, A, A)
9×6 SparseMatrixCSC{Float64, Int64} with 18 stored entries:
0.465226 0.473656 ⋅ ⋅ ⋅ ⋅
0.230678 0.391924 ⋅ ⋅ ⋅ ⋅
0.928409 0.772551 ⋅ ⋅ ⋅ ⋅
⋅ ⋅ 0.465226 0.473656 ⋅ ⋅
⋅ ⋅ 0.230678 0.391924 ⋅ ⋅
⋅ ⋅ 0.928409 0.772551 ⋅ ⋅
⋅ ⋅ ⋅ ⋅ 0.465226 0.473656
⋅ ⋅ ⋅ ⋅ 0.230678 0.391924
⋅ ⋅ ⋅ ⋅ 0.928409 0.772551
如果你真的需要 M为了密集,你可以把它转换回来
julia> Matrix(M)
9×6 Matrix{Float64}:
0.465226 0.473656 0.0 0.0 0.0 0.0
0.230678 0.391924 0.0 0.0 0.0 0.0
0.928409 0.772551 0.0 0.0 0.0 0.0
0.0 0.0 0.465226 0.473656 0.0 0.0
0.0 0.0 0.230678 0.391924 0.0 0.0
0.0 0.0 0.928409 0.772551 0.0 0.0
0.0 0.0 0.0 0.0 0.465226 0.473656
0.0 0.0 0.0 0.0 0.230678 0.391924
0.0 0.0 0.0 0.0 0.928409 0.772551

关于matrix - 如何在 Julia 中以对角线形式连接矩阵,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67548845/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com