combinations with 2 columns
7 次查看(过去 30 天)
显示 更早的评论
Hi guys can you help out in creating a combination
if we got 2 columns and 3 rows
1 2
1 2
1 2
Combination 1: 1,1,1
Combination 2: 1,1,2
Combination 3: 1,2,1
Combination 4:2,1,1
Combination 6: 2,2,2
Combination 7: 2,2,1
Combination 8: 2,1,2
Combination 9: 1,2,2
0 个评论
回答(3 个)
Athul Prakash
2019-10-21
Hi Sampath,
Look like you want to select exactly 1 element per row, from among all columns of the matrix. Hence, if there are m rows and n elements per row (or n columns), there would be n^m combinations generated (2^3 = 8 in your question).
Solution using combvec()
Please read up on combvec here:
If we give row vectors as inputs to combvec(), it generates all possible combinations of elements from those row vectors. Hence, we may pass each row to combvec() as a separate argument, as illustrated below:
mat = [1 2; 1 2; 1 2];
ans = combvec(mat(1,:), mat(2,:), mat(3,:)) % Each column of 'ans' is one of your desired combinations
If the number of rows is not known, you may want to use a for loop:
% suppose 'mat' contains the data
num_rows = size(mat,1);
combs = mat(1,:);
for i=2:num_rows
combs = combvec(mat(i,:), combs);
end
disp(combs);
Hope it Helps!
0 个评论
Jos (10584)
2019-10-21
Take a look at ALLCOMB on the File Exchange:
X = [1 2 ; 3 4 ; 5 6] ; % input matrix
[n, m] = size(X) % [n m]
C = mat2cell(X, ones(1,n), m)
B = allcomb(C{:})
0 个评论
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Logical 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!