I need some code review…
Suppose you are given a matrix A \in \mathbb{N}^{m \times n} you are to determine all the rows k \leq m of A that have a given maximum interaction j which is given by
Here’s an example. Take
julia> inds
15×4 Array{Int64,2}:
0 0 0 0
1 0 0 0
0 1 0 0
0 0 1 0
0 0 0 1
2 0 0 0
1 1 0 0
1 0 1 0
1 0 0 1
0 2 0 0
0 1 1 0
0 1 0 1
0 0 2 0
0 0 1 1
0 0 0 2
and set j = 2, then
julia> get_interaction(inds,2)
6×4 Array{Int64,2}:
1 1 0 0
1 0 1 0
1 0 0 1
0 1 1 0
0 1 0 1
0 0 1 1
So, the function get_interaction
finds all rows of a matrix that have j non-zero entries.
function get_interaction(inds::Matrix{Int},j::Int)
M = .!(iszero.(inds)) # auxiliary variable that is true for every non-zero element of inds
J = findall(x->x==j,sum(M;dims=2))
vcat(map(j->inds[j.I[1],:],J)'...) # return as a matrix of integers
end
This is one way to implement this, but it feels too bulky. There’s probably a more clever way to exploit the CartesianIndices returned by findall
.
thanks!
p.s.: The last row could be simplified to the more performant
map(j->inds[j.I[1],:],J)
which would return an arrray of arrays of integers
julia> get_interaction(inds,2)
6-element Array{Array{Int64,1},1}:
[1, 1, 0, 0]
[1, 0, 1, 0]
[1, 0, 0, 1]
[0, 1, 1, 0]
[0, 1, 0, 1]
[0, 0, 1, 1]