Loop over combinations of elements of several vectors
13 visualizaciones (últimos 30 días)
Mostrar comentarios más antiguos
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 comentarios
Respuestas (2)
Dyuman Joshi
el 18 de Oct. de 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 comentarios
Chunru
el 18 de Oct. de 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 comentario
Ver también
Categorías
Más información sobre Loops and Conditional Statements en Help Center y File Exchange.
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!