首页 > 解决方案 > MATLAB - 如何梳理()单元格?

问题描述

假设我的向量不包含双打。它们包含细胞。combvec拒绝接受单元格值...例如:

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

我想以某种方式获得一个单元格向量的向量,其中包含所有可能的单元格组合:[[cell1, cell4, cell6]; [cell1, cell5, cell6]; [cell2, cell4, cell6]; [cell2, cell5, cell6]; [cell3, cell4, cell6]; [cell3, cell5, cell6];];.

如何做呢?

PS我这样做的原因是因为我已经对项目进行了分组,并且我想找到它们的所有组合,所以我想将它们插入到 nx1 单元格中。如果有更好的解决方案,请指教...

标签: matlabcombinatoricscell-array

解决方案


只需combvec与表示列索引的整数数组一起使用,然后使用它来索引您的原始数组

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,:))];

你可以这样概括(可能有更简洁的方法)

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]}

推荐阅读