Obtain every possible combination in array
7 次查看(过去 30 天)
显示 更早的评论
I have 3, 100 x 1 vectors that I am combining to make a m x 4 matrix. To obtain 4 columns in the desired output, two elements from the first vector are selected as the first two elements in a row, and then one element from the second vector as the third element, and one element from the third vector as the fourth element to complete the m x 4. I would like to get every possible row combination possible in one large matrix. I started with a huge nested for loop and quickly got lost and assume there must be a better way. Any help is appreciated.
4 个评论
Kirby Fears
2017-3-30
编辑:Kirby Fears
2017-3-30
The combinations total to (100)*99/2*100*100 = 49,500,000 rows. It's probably worth rethinking this approach. I will post some code below anyway...
回答(1 个)
Kirby Fears
2017-3-30
编辑:Kirby Fears
2017-5-8
Here's a brute force generation of all combinations. Memory usage is more of a bottleneck than processing time, so I wrote it with for-loops.
Note that storing all combinations may not be the best approach to address your underlying use case.
Set sz = 100 to match your vector size; beware of 50 million rows.
% Setting up dummy data
sz = 10; % 4500 rows
a = (1:sz)';
b = a + sz;
c = b + sz;
res = NaN(sz^3*(sz-1)/2,4);
% Filling array with selections
iCounter = 0;
for ai = 1:(numel(a)-1),
for aj = (ai+1):numel(a),
for bi = 1:sz,
for ci = 1:sz,
iCounter = iCounter + 1;
res(iCounter,:) = [a(ai) a(aj) b(bi) c(ci)];
end
end
end
end
2 个评论
Ahmed Ibrahim
2017-5-7
If each element of vector with size (1,14) takes one value from this vector [0 0.625 1.25 2.5] . How can I obtain all possible combinations of this vector ?
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Matrices and Arrays 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!