MATLAB中combvec不支持单元格数组时,如何生成全组合?
解决Cell数组的全组合生成问题
嘿,我懂你的痛点——combvec确实只认数值数组,对cell数组直接罢工。不过咱们完全可以手动实现一个等价的功能,精准生成你要的所有cell组合。
先看你的需求:输入是一个多行的cell数组m,每行代表一组可选元素,要从每行选一个元素,生成所有可能的组合矩阵。就像你给的例子,3行分别有3、2、1个cell,最终要输出6种组合。
针对你的特定场景(固定3行)的实现代码
% 你的原始cell数组输入 m = { [cell1, cell2, cell3]; [cell4, cell5]; [cell6]; }; % 第一步:获取每行的元素个数 row_lengths = cellfun(@length, m); % 这里会得到 [3, 2, 1] % 第二步:生成所有可能的索引组合网格 [idx1, idx2, idx3] = ndgrid(1:row_lengths(1), 1:row_lengths(2), 1:row_lengths(3)); % 第三步:把索引网格转成列向量,方便一一对应组合 idx1 = idx1(:); idx2 = idx2(:); idx3 = idx3(:); % 第四步:根据索引提取cell元素并组合成单个cell数组 combinations = cellfun(@(i,j,k) {m{1,i}, m{2,j}, m{3,k}}, idx1, idx2, idx3, 'UniformOutput', false); % 第五步:转换成你要的矩阵形式(每一行是一个组合) result = vertcat(combinations{:});
运行这段代码后,result就是你想要的结构:
[[cell1, cell4, cell6]; [cell1, cell5, cell6]; [cell2, cell4, cell6]; [cell2, cell5, cell6]; [cell3, cell4, cell6]; [cell3, cell5, cell6];]
通用版本(支持任意行数的cell数组)
如果你的m行数不固定(比如可能是2行、4行),可以用这个通用版,不用手动修改行数相关的代码:
% 任意行数的cell数组输入 m = { [cell1, cell2, cell3]; [cell4, cell5]; [cell6]; }; % 可替换成N行的cell数组 % 获取每行元素个数和总行数 row_lengths = cellfun(@length, m); total_rows = length(row_lengths); % 生成通用的索引网格(用可变参数处理任意维度) [indices{1:total_rows}] = ndgrid(arrayfun(@(x) 1:x, row_lengths, 'UniformOutput', false){:}); % 把每个索引网格转成列向量 indices = cellfun(@(x) x(:), indices, 'UniformOutput', false); % 遍历所有索引组合,生成对应的cell组合 total_combinations = size(indices{1}, 1); result = cell(total_combinations, 1); for i = 1:total_combinations result{i} = cell(1, total_rows); for j = 1:total_rows result{i}{j} = m{j, indices{j}(i)}; end end % 转换成最终的矩阵形式 result = vertcat(result{:});
这个版本不管你输入的m有多少行,都能自动计算所有可能的组合,灵活性拉满~
内容的提问来源于stack exchange,提问作者MattS
相关产品推荐
相关产品推荐

