Consider this solution using the NDGRID function:
sets = {[1 2], [1 2], [4 5]}; [xyz] = 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
Or, if you want a general solution for any number of sets (without having to create variables manually), use this function definition:
function result = cartesianProduct(sets) c = cell(1, numel(sets)); [c{:}] = ndgrid( sets{:} ); result = cell2mat( cellfun(@(v)v(:), c, 'UniformOutput',false) ); end
Please note: if you prefer, you can sort the results:
cartProd = sortrows(cartProd, 1:numel(sets));
In addition, the above code does not check for sets of duplicate values ββ(for example: {[1 1] [1 2] [4 5]} ). Add this line if you want:
sets = cellfun(@unique, sets, 'UniformOutput',false);
Amro Nov 12 '10 at 10:06
source share