我有一个稀疏对称矩阵,代表某本书的作者。如果与索引 i 和 j 相关联的人是合著者,则元素 Ai,j 和 Aj,i 都等于 1,否则都等于 0。我试图在矩阵表示中找到一种方法,以便在给定两列(作者)的情况下找到他们共同的合著者。最好用 Matlab 或 Julia 代码表示。
最佳答案
列之间的二进制 &
,按元素应用,将返回一个带有 1
的向量,仅当两列都有 1
时。您可以对其执行 findall
,然后返回结果为 1
的索引,这表示共同的合著者。
julia> A
5×5 SparseMatrixCSC{Bool, Int64} with 12 stored entries:
⋅ 1 ⋅ 1 1
1 ⋅ ⋅ ⋅ 1
⋅ ⋅ ⋅ ⋅ 1
1 ⋅ ⋅ ⋅ 1
1 1 1 1 ⋅
julia> common = A[:, 1] .& A[:, 5]
5-element SparseVector{Bool, Int64} with 2 stored entries:
[2] = 1
[4] = 1
julia> findall(common)
2-element Vector{Int64}:
2
4
这会在 Julia 中找到作者 1 和 5 之间的共同合著者。 &
之前的 .
表示应按元素应用运算符。为了概括这一点,您可以将其编写为如下函数:
julia> function findcommoncoauths(adjmat, author1, author2)
@views findall(adjmat[:, author1] .& adjmat[:, author2])
end
(@views
是为了避免为列分配不必要的新内存,这是高性能代码的良好实践。)
关于matlab - 从对称邻接矩阵中的两列中查找公共(public)元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/74163169/