enigmae
enigmae

Reputation: 349

Finding subsets inside a cell array

Consider a cell array, I, where

I = { [i_1 ; i_2 ; .... ; i_n] [i_1,i_2 ; i_1,i_3; ...; i_n,i_n-1 ].. [ % all NCi combinations] ...}

Now, I want to find the number of times each row of each cell appears as a subset of another row of a different cell.

For example, I want to find the number of times i_1, i_2 appear together in the same row in the whole cell array.

I = {[1;2;3] [(1,2);(2,3);(1,3)] [1,2,3]}

ans = 2. (once in the 1st row of the 2nd cell and once in the only row of the 3rd cell).

I have been trying different things with this member but I'm just not able to get it. Any ideas?

Upvotes: 0

Views: 78

Answers (2)

Jonas
Jonas

Reputation: 74940

Here's a solution that makes use of the "rows" argument of ismember (note that [1 2] will be found in [1 2 3] with this approach).

I = {[1;2;3],[1,2;2,3;1,3],[1,2,3]};
bait = [1 2];
baitCols = size(bait,2);

%# identify cells with sufficient columns for comparison
goodIdx = cellfun(@(x)size(x,2) >= baitCols,I);

%# count all occurrences
count = sum(cellfun(@(x)sum(ismember(x(:,1:baitCols),bait,'rows')),I(goodIdx)));

Upvotes: 1

tashuhka
tashuhka

Reputation: 5126

Fast and dirty loop:

 I = {[1;2;3],[1,2;2,3;1,3],[1,2,3]};
 i_1 = 1;
 i_2 = 2;

 count = 0;
 for ii=1:numel(I),
     for jj=1:size(I{ii},1)
         if any(I{ii}(jj,:)==i_1) && any(I{ii}(jj,:)==i_2)
             count = count+1;
         end
     end
 end

Upvotes: 0

Related Questions