Reputation: 109
I have a two cell arrays R and C (two vectors with R(n-elements), C(m-elements)) and my task is to compare each element of R with each element of R and each element of C with each element of C. Comparison is to finding intersection of two cells. In result I want to obtain two matrices. One matrix Q for R nxn, where in cell Q(i,j) is intersection of two elements R(i) and R(j) and second matrix P for C mxm, where in cell P(i,j) is intersection of two elements C(i) and C(j).
Generally I can do this using two for-loops, but my data is quite big and I wonder if there is any method to speed up the computation?
The first idea was to replace the cell array, where in each cell are the indexes of rows (vector R) or columns (vector C) which I want to compare (rows and columns of binary matrix BM, BM is input data) . So If R(1) = {2 3 4}
, and BM is 5x5, then R(1,:)=[0 1 1 1 0]
. Now having this binary matrix R I could compare each row with each row only with one loop. But then I still need to come back to number of rows eg
R(1,:) = [0 1 1 1 0];
R(2,:) = [0 1 1 0 0]; %then
Q(1,2) = [0 1 1 0 0]; %(intersection of element R(1) and R(2)) and
C(1,:) = [1 1 0 0 0];
C(2,:) = [1 0 0 1 0]; %then
P(1,2) = [1 0 0 0 0]; % Now I want to obtain
Results(i,j) = sum(BM(Q(1,2),P(1,2)))=sum(BM([2 3],[1]));
Do you have any idea how to cope with this, and compare two vectors of cell array without a two loops?
Upvotes: 1
Views: 1473
Reputation: 114786
Since Q( k, l )
is a vector with numCols (5 in your example) it cannot be stored in a 2D matrix Q
: Q
should either be a 2D cell array, or a 3D matrix.
Using the binary matrix directly to obtain Q
(row intersections):
>> Q = bsxfun( @times, permute( BM, [1 3 2] ), permute( BM, [3 1 2] ) );
Now, Q( k, l, : )
holds the intersection betwee the k
-th and l
-th rows of BM
.
Same goes for P
:
>> P = bsxfun( @times, permute( BM, [3 2 1] ), permute( BM, [2 3 1] ) );
Upvotes: 1