Create a Cartesian product with user-specified constraints
Hello,
I’m trying to figure out how to code a simple and flexible cartesian product function
To abstract how it works conceptually, let’s imagine we have a 4 X 10 matrix, with each column having ordered values 1 through 4, like this
1 1 1 1 1 1 etc
2 2 2 2 2 2 etc
3 3 3 3 3 3 etc
4 4 4 4 4 4 etc
The user specifies the number of rows and columns to be used to make the cartesian product. For example, if they specify 2 rows and 3 columns, the result should be (although the order doesn’t matter)
1 1 1
1 1 2
1 2 1
2 1 1
1 2 2
2 1 2
2 2 1
2 2 2
The closest function that I’ve found is
function C = cartesian(varargin)
% This function creates cartesian products from input arrays
args = varargin;
n = nargin;
[F{1:n}] = ndgrid(args{:});
for i=n:-1:1
G(:,i) = F{i}(:);
end
C = unique(G , ‘rows’);
end
However, it asks for a series of arrays as input. In my case, I need the input to be a matrix of variable dimensions. Thank you for any help!Hello,
I’m trying to figure out how to code a simple and flexible cartesian product function
To abstract how it works conceptually, let’s imagine we have a 4 X 10 matrix, with each column having ordered values 1 through 4, like this
1 1 1 1 1 1 etc
2 2 2 2 2 2 etc
3 3 3 3 3 3 etc
4 4 4 4 4 4 etc
The user specifies the number of rows and columns to be used to make the cartesian product. For example, if they specify 2 rows and 3 columns, the result should be (although the order doesn’t matter)
1 1 1
1 1 2
1 2 1
2 1 1
1 2 2
2 1 2
2 2 1
2 2 2
The closest function that I’ve found is
function C = cartesian(varargin)
% This function creates cartesian products from input arrays
args = varargin;
n = nargin;
[F{1:n}] = ndgrid(args{:});
for i=n:-1:1
G(:,i) = F{i}(:);
end
C = unique(G , ‘rows’);
end
However, it asks for a series of arrays as input. In my case, I need the input to be a matrix of variable dimensions. Thank you for any help! Hello,
I’m trying to figure out how to code a simple and flexible cartesian product function
To abstract how it works conceptually, let’s imagine we have a 4 X 10 matrix, with each column having ordered values 1 through 4, like this
1 1 1 1 1 1 etc
2 2 2 2 2 2 etc
3 3 3 3 3 3 etc
4 4 4 4 4 4 etc
The user specifies the number of rows and columns to be used to make the cartesian product. For example, if they specify 2 rows and 3 columns, the result should be (although the order doesn’t matter)
1 1 1
1 1 2
1 2 1
2 1 1
1 2 2
2 1 2
2 2 1
2 2 2
The closest function that I’ve found is
function C = cartesian(varargin)
% This function creates cartesian products from input arrays
args = varargin;
n = nargin;
[F{1:n}] = ndgrid(args{:});
for i=n:-1:1
G(:,i) = F{i}(:);
end
C = unique(G , ‘rows’);
end
However, it asks for a series of arrays as input. In my case, I need the input to be a matrix of variable dimensions. Thank you for any help! cartesian product MATLAB Answers — New Questions









