Loop over combinations of elements of several vectors
5 views (last 30 days)
Show older comments
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 Comments
Answers (2)
Dyuman Joshi
on 18 Oct 2023
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 Comments
Chunru
on 18 Oct 2023
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 Comment
See Also
Categories
Find more on Loops and Conditional Statements in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!