Search code examples
matlabuniquecell-arraycells

Unique columns based on cell array


Say I have a cell array in the following format:

A = {4;[22 16 4]; 23; 51; [16 22]; 32; [4 50]}; 

I want to output the unique columns gained by any permutations of the vectors in the rows. For example, for the example in the above, the only column vectors that would satisfy this would be [4; 22; 23; 51; 16; 32; 50] and [4; 16; 23; 51; 22; 32; 50].

I can't choose 4 from the second or last rows since 4 is the only option in the first row. Moreover, I can't choose 22 in both the second and fifth rows since this would make the column non-unique. Although empty choices in some rows are not allowed, if there are no unique columns, then I would need to output an empty column.

Does anyone have a smart way of doing this (fairly quickly) in Matlab? Any help would be much appreciated. Many thanks!


Solution

  • Here's a brute-force approach:

    1. Generate all possible columns obtained by choosing one element from each vector (Cartesian product). This can be done with this approach.
    2. Keep only those columns for which all elements are different. This is easily done with sort, diff, all, and logical indexing.

    Code:

    A = {4; [22 16 4]; 23; 51; [16 22]; 32; [4 50]};  % Data
    n = numel(A);                                     % Step 1
    c = cell(1,n);
    [c{end:-1:1}] = ndgrid(A{:});
    c = cat(n+1, c{end:-1:1});
    c = reshape(c,[],n).'; % Step 1
    result = c(:,all(diff(sort(c,1),[],1),1));        % Step 2