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.
![](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 个评论
回答(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 中查找有关 Creating and Concatenating Matrices 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!