Loop over combinations of elements of several vectors
조회 수: 5 (최근 30일)
이전 댓글 표시
In the simplest case, if I have vectors , I want to loop over all the possible combinations of their elements, that is, over I wat to do the same thing in a general case where I have and arbitrary number of vectors with respective dimensions , with denoting the k-th component of vector ; that is, I want to loop over all the combinations of elements . How to do this for a general number of vectors? For now, the only thing I came up with is to make nested loops for each vector, but I want some code whose structure does not depend on the number of vectors.
Thanks for your time!
댓글 수: 0
답변 (2개)
Dyuman Joshi
2023년 10월 18일
x1 = 1:5;
x2 = [2 3 5 7 11];
x3 = [2 4 6 8 10];
%Store vectors in a cell array
x = {x1,x2,x3};
n = numel(x);
%Preallocate
C = cell(1,n);
%Reverse order to get the proper order when concatenating
[C{end:-1:1}] = ndgrid(x{end:-1:1});
%Concatenate and reshape the data corresponding to number of vectors
out = reshape(cat(n,C{:}),[],n);
disp(out)
댓글 수: 0
Chunru
2023년 10월 18일
You can use combinations.
% arbitrary number of vectors with arbitrary size
v{1}=rand(3,1);
v{2}=rand(2,1);
v{3}=rand(2,1);
p =table2array(combinations(v{:}))
for i=1:size(p,1) % only one loop instead of nested loop
p(i, :) % this is the combination and do whatever you want in the loop
end
댓글 수: 1
참고 항목
카테고리
Help Center 및 File Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!