cartesianprod(varar​gin)

Version 1.3.0.0 (4.33 KB) by Mike Unit
Efficiently creates the Cartesian Product of n vectors
49 Downloads
Updated 17 Feb 2016

View License

Wrapper for meshgrid(), which creates all combinations of the elements of
the vectors stored in the cellarray 'fields'. The output is either i) a
cellarray of combinations, each given as a string where the original
elements are separated by 'delim', or ii) a row-indexed matrix of
combinations of the original elements. All component vectors must be of
the same type (all cell arrays or all doubles). See the following examples.
Example 1:
fields{1} = {'a';'b'};
fields{2} = {'c';'d';'e'};
fields{3} = {'f';'g'};
delim = '_';
out = cartesianprod(fields,delim);
out =
'a_c_f'
'a_c_g'
'a_d_f'
'a_d_g'
'a_e_f'
'a_e_g'
'b_c_f'
'b_c_g'
'b_d_f'
'b_d_g'
'b_e_f'
'b_e_g'
Example 2:
fields{1} = {'a';'b'};
fields{2} = {'c';'d';'e'};
fields{3} = {'f';'g'};
out = cartesianprod(fields);
out =

'a' 'c' 'f'
'a' 'c' 'g'
'a' 'd' 'f'
'a' 'd' 'g'
'a' 'e' 'f'
'a' 'e' 'g'
'b' 'c' 'f'
'b' 'c' 'g'
'b' 'd' 'f'
'b' 'd' 'g'
'b' 'e' 'f'
'b' 'e' 'g'
Example 3:
fields{1} = [1;2];
fields{2} = [3;4;5];
fields{3} = [6;7];
out = cartesianprod(fields);
out =
1 4 6
1 4 7
1 5 6
1 5 7
2 4 6
2 4 7
2 5 6
2 5 7
3 4 6
3 4 7
3 5 6
3 5 7

Cite As

Mike Unit (2024). cartesianprod(varargin) (https://www.mathworks.com/matlabcentral/fileexchange/55328-cartesianprod-varargin), MATLAB Central File Exchange. Retrieved .

MATLAB Release Compatibility
Created with R2014a
Compatible with any release
Platform Compatibility
Windows macOS Linux
Categories
Find more on Directed Graphs in Help Center and MATLAB Answers

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!
Version Published Release Notes
1.3.0.0

Faster code.

1.2.0.0

Updated description and added an error check - all component vectors must be either cell arrays or doubles.

1.1.0.0

Updated the description.

1.0.0.0