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!
댓글 수: 4
The question is a bit ambiguous as to what portion of the array is to be selected. Is it leading rows and leading columns, or tailing rows and trailing columns? It matters if for example
M = magic(5)
Emmanuel
2026년 3월 3일 22:00
"I just had to transpose my 'cartesian_index' matrix before splitting it."
You don't have to transpose anything, just split on the correct dimension:
nR = 2;
nC = 3;
X = repmat(1:nR,nC,1);
C = num2cell(X,2);
D = cartesian1(C{:})
The function is simpler and likely more efficient without UNIQUE and the FOR loop:
function M = cartesian1(varargin)
[varargin{:}] = ndgrid(varargin{:});
M = reshape(cat(nargin+1, varargin{:}), [], nargin);
end
As posed creating that full matrix is superfluous anyway, you don't even need to duplicate all of those vectors, so you could make the whole thing simpler with one single vector:
nR = 2;
nC = 3;
D = cartesian2(1:nR,nC)
function M = cartesian2(V,nC)
[C{1:nC}] = ndgrid(V);
M = reshape(cat(nC+1, C{:}), [], nC);
end
Emmanuel
2026년 3월 5일 17:13
채택된 답변
추가 답변 (0개)
카테고리
도움말 센터 및 File Exchange에서 Matrix Indexing에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!