I have a sparse symmetric matrix which represents authors of some book. Elements Ai,j and Aj,i are both equal to one if the people associated with indices i and j are coauthors and equal to zero otherwise. I'm trying to find a way in matrix representation such that given two columns (authors), I find their common co-authors. Preferably in Matlab or Julia code representation.
The binary &
between the columns, applied elementwise, will return a vector with 1
s only where both columns had 1
s. You can do a findall
over that to then return the indices where the result is 1
, which indicates the common co-authors.
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
This finds the common co-authors between authors 1 and 5, in Julia. The .
before the &
indicates that the operator should be applied elementwise. To generalize this, you can write it as a function like:
julia> function findcommoncoauths(adjmat, author1, author2)
@views findall(adjmat[:, author1] .& adjmat[:, author2])
end
(The @views
is to avoid unnecessarily allocating new memory for the columns, which is a good practice for performant code.)