Loop over combinations of elements of several vectors
6 Ansichten (letzte 30 Tage)
Ältere Kommentare anzeigen
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.
![](https://www.mathworks.com/matlabcentral/answers/uploaded_files/1514164/image.png)
![](https://www.mathworks.com/matlabcentral/answers/uploaded_files/1514169/image.png)
![](https://www.mathworks.com/matlabcentral/answers/uploaded_files/1514174/image.png)
![](https://www.mathworks.com/matlabcentral/answers/uploaded_files/1514179/image.png)
![](https://www.mathworks.com/matlabcentral/answers/uploaded_files/1514184/image.png)
![](https://www.mathworks.com/matlabcentral/answers/uploaded_files/1514189/image.png)
![](https://www.mathworks.com/matlabcentral/answers/uploaded_files/1514194/image.png)
Thanks for your time!
0 Kommentare
Antworten (2)
Dyuman Joshi
am 18 Okt. 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 Kommentare
Chunru
am 18 Okt. 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 Kommentar
Siehe auch
Kategorien
Mehr zu Creating and Concatenating Matrices finden Sie in Help Center und File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!