temp = 1;
for level = 1:size(overlap,2)
temp = bsxfun(@and, temp, permute(overlap,[1 3:1+level 2]));
result{level} = squeeze(sum(temp));
end
How the result is interpreted
The variable result
is a cell array which contains the results for all levels. Let n denote the number of columns in overlap
.
Level 1:
result{1}
is a 1 x n vector which gives the intersection of each column ofoverlap
with itself (i.e. the sum of each column). For example,result{1}(4)
is the number of ones in column 4 ofoverlap
.Level 2:
result{2}
is an n x n matrix. For example,result{2}(4,2)
is the intersection of columns 4 and 2 ofoverlap
. (result{2}
ismat
in the original post).Level 3:
result{3}
is an n x n x n array. For example,result{3}(4,2,5)
is the intersection of columns 4, 2 and 5 ofoverlap
.[...] until level n.
How the code works
When computing the result at a given level, the code makes use of intermediate results from the previous level. This can be done because the "and" operation is associative. For example, at level 3, overlap(:,k) & overlap(:,m) & overlap(:,p)
can be computed as (overlap(:,k) & overlap(:,m)) & overlap(:,p)
, where overlap(:,k) & overlap(:,m)
was already computed (and stored) at level 2.
The final result at each level (result{level}
) will be obtained as a column-wise sum. However, the intermediate result before that sum is stored (variable temp
) to be re-used at the next level.
Each new level takes the intermediate result from the preceding level (temp
), adds a new dimension (permute
) and computes (bsxfun
) the new intermediate result (new value of temp
, with one more dimension). That intermediate result, upon column-wise sum
(and squeeze
to remove singleton dimensions), gives that level's final result (result{level}
).