Search code examples
matlabcombinatoricscell-array

MATLAB - how to combvec() cells?


Let's say my vectors don't contain doubles. They contain cells. combvec refuses to accept cell values... for example:

m = {
    [cell1, cell2, cell3];
    [cell4, cell5];
    [cell6];
    };

I want to somehow get a vector of vector of cells, containing all possible combinations of cells: [[cell1, cell4, cell6]; [cell1, cell5, cell6]; [cell2, cell4, cell6]; [cell2, cell5, cell6]; [cell3, cell4, cell6]; [cell3, cell5, cell6];];.

How can it be done?

P.S. The reason I'm doing this is because I have grouped items, and I want to find all combinations of them, so I thought inserting them into nx1 cells. If there's a better solution, please advise...


Solution

  • Just use combvec with arrays of integers representing the column index, then use that to index your original array

    C = {[{1} {2} {3}]; [{4} {5}]; [{6}]}
    cv = combvec(1:3, 1:2, 1)
    
    out = [C{1}(1,cv(1,:)); C{2}(1,cv(2,:)); C{3}(1,cv(3,:))];
    

    You could generalise this like so (there may be a neater way)

    idx = cellfun(@(x) 1:numel(x), C, 'uni', 0); % set up indexing array
    cv = combvec(idx{:}); % get combinations
    
    out = arrayfun(@(x) C{x}(1,cv(x,:)), 1:3, 'uni', 0); % index into the cell array
    out = vertcat(out{:}); % concatenate results
    
    % Result
    >> out = 
    {[1]}    {[2]}    {[3]}    {[1]}    {[2]}    {[3]}
    {[4]}    {[4]}    {[4]}    {[5]}    {[5]}    {[5]}
    {[6]}    {[6]}    {[6]}    {[6]}    {[6]}    {[6]}