How to generate all d combinations of elements of a vector of length M?
2 次查看(过去 30 天)
显示 更早的评论
Hello all,
I have a vector of H length M; I would like to create a new matrix V with size dx(M^d), where each column of V contains each different d combinations of elements of M. For instance, if H=[1+i 2 1-i 1 0 -1-i 5 -1+i] and d=2, I would like to get a 2x(M^2)=2x64 matrix with the following columns: V1(first column of V)=[1+i 1+i].'; V2(second column of V)=[1+i 2].'; V3=[1+i 1-i].'; .... Can somebody please help me? Thank you!
0 个评论
回答(1 个)
Image Analyst
2016-1-26
I think this works, but I'm only getting 28 combinations if you have 8 elements and you take all combinations of 2 at a time:
H=[1+i,... % Element #1
2,... % Element #2
1-i,... % Element #3
1,... % Element #4
0,... % Element #5
-1-i,... % Element #6
5,... % Element #7
-1+i] % Element #8
M = length(H);
d = 2; % user specified
logicalIndexes = dec2bin(0:2^M-1) == '1'
% Find those rows where the number of elements is d:
rowsToExtract = sum(logicalIndexes, 2) == d
logicalIndexes = logicalIndexes(rowsToExtract, :) % Rows with only 2 elements
numCombinations = sum(rowsToExtract);
% Extract those rows from H
Hout = zeros(numCombinations, d)
% Load up Hout
for row = 1 : numCombinations
theseColumns = find(logicalIndexes(row,:))
for k = 1 : d
Hout(row, k) = H(theseColumns(k))
end
end
% Print to command window:
Hout
size(Hout)
0 个评论
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Operating on Diagonal Matrices 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!