create a matrix of combinations

1 次查看(过去 30 天)
Colby
Colby 2016-7-20
回答: BhaTTa 2024-8-29
Hello,
I'm trying to create a matrix with all possible combinations of combinations I guess.
If I run the follow code
n = 2 ; % number of canidates
sp = 4;% number of periods
M = dec2bin(0:(2^n)-1)-'0';
A = [1:sp];
for i = 2:size(M,1)
A = [A, 1:sp];
end
A = sort(A');
cnt = 1;
cnt2 = 0;
B = [M;M];
while size(B,1) < size(A,1)
B = [B;M];
end
C = [A,B];
I get the matrix C, with all possible combinations of candidates (columns 2 and 3), for every period (column 1). Now I would like to get a matrix that has all possible combinations of selecting one combination form each period.
So possible combinations would be 1 0 0, 2 0 0, 3 0 0, 4 0 0, or 1 0 1, 2 0 0, 3 0 0, 4 0 0, or 1 0 0, 2 0 1, 3 0 0, 4 0 0 and so on. Each combination must go 1xx 2xx 3xx 4xx. Does anyone know how I could get MATLAB to produce all the possible combinations?
Thank you so much for your time Colby

回答(1 个)

BhaTTa
BhaTTa 2024-8-29
To generate all possible combinations of selecting one combination from each period, you can use the concept of Cartesian products. In your context, you want to select one row from each period's combinations. Here's how you can achieve this in MATLAB:Step-by-Step Solution
  1. Generate the Initial Combinations: You've already done this part, where you have the matrix C with all possible combinations for each period.
  2. Group by Period: For each period, extract its corresponding combinations.
  3. Generate All Possible Selections: Use a nested loop or a more efficient approach to generate all possible selections of one combination per period.
Here's how you can implement this:
n = 2; % number of candidates
sp = 4; % number of periods
% Generate all combinations for one period
M = dec2bin(0:(2^n)-1) - '0';
% Prepare matrix C with all combinations for each period
A = repmat((1:sp)', size(M, 1), 1);
B = repmat(M, sp, 1);
C = [A, B];
% Initialize a cell array to hold combinations for each period
periodCombinations = cell(sp, 1);
% Group combinations by period
for i = 1:sp
periodCombinations{i} = C(C(:, 1) == i, :);
end
% Generate all possible selections
allSelections = cell(1, sp);
[allSelections{:}] = ndgrid(1:size(M, 1));
allSelections = cellfun(@(x) x(:), allSelections, 'UniformOutput', false);
allSelections = [allSelections{:}];
% Build the final matrix with all possible selections
finalCombinations = zeros(size(allSelections, 1), sp * (n + 1));
for i = 1:size(allSelections, 1)
for j = 1:sp
rowIdx = allSelections(i, j);
finalCombinations(i, (j-1)*(n+1)+1:j*(n+1)) = periodCombinations{j}(rowIdx, :);
end
end
% Display the result
disp(finalCombinations);

类别

Help CenterFile Exchange 中查找有关 Matrices and Arrays 的更多信息

标签

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by