考虑使用此解决方案NDGRID http://www.mathworks.com/help/techdoc/ref/ndgrid.html功能:
sets = {[1 2], [1 2], [4 5]};
[x y z] = ndgrid(sets{:});
cartProd = [x(:) y(:) z(:)];
cartProd =
1 1 4
2 1 4
1 2 4
2 2 4
1 1 5
2 1 5
1 2 5
2 2 5
或者,如果您想要任意数量的集合的通用解决方案(无需手动创建变量),请使用以下函数定义:
function result = cartesianProduct(sets)
c = cell(1, numel(sets));
[c{:}] = ndgrid( sets{:} );
result = cell2mat( cellfun(@(v)v(:), c, 'UniformOutput',false) );
end
请注意,如果您愿意,可以对结果进行排序:
cartProd = sortrows(cartProd, 1:numel(sets));
此外,上面的代码不会检查集合是否没有重复值(例如:{[1 1] [1 2] [4 5]}
)。如果您想添加这一行:
sets = cellfun(@unique, sets, 'UniformOutput',false);