n-fold Cartesian product

조회 수: 4 (최근 30일)
Sundar Aditya
Sundar Aditya 2016년 5월 5일
댓글: Sundar Aditya 2016년 5월 6일
I need to compute the n-fold Cartesian product of a set, where n is a positive integer determined by some previous code. Is there any way to do this without using nested for-loops? ndgrid seems to be optimal for a fixed n, but I'm unable to find a solution for any general n. Thanks.

채택된 답변

John D'Errico
John D'Errico 2016년 5월 5일
For example:
S = 1:3;
n = 5;
q = cell(1,5);
s = repmat({S},1,n);
[Q{1:n}] = ndgrid(s{:});
Q = reshape(cat(n,Q{:}),[],n);
I'm not sure if that solution is a trivial one. Trivial is all in the eyes of the beholder anyway. To be honest, I've written a function in one of my toolboxes that does it for me, rather than have to remember this trick when I need it.
  댓글 수: 1
Sundar Aditya
Sundar Aditya 2016년 5월 6일
Thanks for the answer, John.

댓글을 달려면 로그인하십시오.

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Read, Write, and Modify Image에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by