MATLAB:任意数量的单元格数组的组合 [英] MATLAB: Combinations of an arbitrary number of cell arrays

查看:130
本文介绍了MATLAB:任意数量的单元格数组的组合的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

MATLAB中是否有一条命令或单行策略可以一次返回n取回n单元格数组的所有组件组合?

Is there a command or one-line strategy in MATLAB that will return all the combinations of the components of n cell arrays, taken n at a time?

我要完成的示例:

A = {'a1','a2'};
B = {'b1','b2','b3'};
C = combinations(A,B)
C = {'a1','b1' ;
     'a1','b2' ;
     'a1','b3' ;
     'a2','b1' ;
     'a2','b2' ;
     ... }

该命令将能够接受任意数量的参数,并且示例中的结果将具有与该函数的参数一样多的列. (当然,以上语法仅用于说明目的,而任何可以生成结果的方法,无论采用哪种格式都适用)

The command would be able to accept an arbitrary number of arguments and the result in the example would have as many columns as there are arguments to the function. (Of course, the syntax above is just meant for illustration and any method that would generate the results whatever the format would fit the bill)

对于矩阵而不是单元格,已经提出了类似的问题,例如链接.许多解决方案都指向FEX提交 allcomb ,但是所有这些解决方案都只是ndgrid的包装,仅适用于双打.对于非数字集有什么建议吗?

Similar questions have been asked for matrices instead of cells, e.g. link. Many solutions point to the FEX submission allcomb, but all such solutions are just wrappers around ndgrid, which only work with doubles. Any suggestions for non numeric sets?

推荐答案

尽管我在我的答案中解决了这个问题相关/近乎重复的问题,我在此处发布了不同版本的解决方案,因为看来您想要一个通用解决方案,而我的其他答案是针对三个输入集的情况.这是一个应针对任何数量的单元格数组输入执行所需操作的函数:

Although I address this in my answer to a related/near duplicate question, I'm posting a different version of my solution here since it appears you want a generalized solution, and my other answer is specific for the case of three input sets. Here's a function that should do what you want for any number of cell array inputs:

function combMat = allcombs(varargin)
  sizeVec = cellfun('prodofsize', varargin);
  indices = fliplr(arrayfun(@(n) {1:n}, sizeVec));
  [indices{:}] = ndgrid(indices{:});
  combMat = cellfun(@(c,i) {reshape(c(i(:)), [], 1)}, ...
                    varargin, fliplr(indices));
  combMat = [combMat{:}];
end

这是您的称呼方式:

>> combMat = allcombs(A, B)

combMat = 

    'a1'    'b1'
    'a1'    'b2'
    'a1'    'b3'
    'a2'    'b1'
    'a2'    'b2'
    'a2'    'b3'

这篇关于MATLAB:任意数量的单元格数组的组合的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆