Combination of elements in 2 different vectors
4 次查看(过去 30 天)
显示 更早的评论
Hello to everyone, I have the following two vectors:
yes = [y1 y2 y3 y4];
no = [n1 n2 n3 n4]
My question is if there is a simple way of doing combinations (just as nchoosek would do) but between these two vectors in the following way:
I need to fill a matrix C, whose elements are described by C_ij, where 'i' is the number of elements from the vectors that we take, and 'j' is the number of elements that are correct (from vector 'yes'). For instance: C_21 = y1·n2 + y1·n3 + y1·n4 + y2·n1 + y2·n3 + y2·n4 + y3·n1 + y3·n2 + y3·n4 + y4·n1 + y4·n2 + y4·n3. Note that a combination where i=j (for example C_22) is not possible, since one element can only be either 'yes' or 'no'.
Many thanks in advance.
0 个评论
回答(1 个)
BhaTTa
2024-7-23
To solve this problem, you can use MATLAB to generate the required combinations and fill the matrix ( C ). The goal is to create a matrix ( C ) where each element ( C_{ij} ) represents the sum of all possible products of i elements, with j of them being from the yes vector.
% Define the vectors
yes = [y1, y2, y3, y4];
no = [n1, n2, n3, n4];
% Define the size of the vectors
n_yes = length(yes);
n_no = length(no);
% Initialize the matrix C
C = zeros(n_yes + n_no, n_yes);
% Loop through the number of elements taken (i)
for i = 1:(n_yes + n_no)
% Loop through the number of correct elements (j)
for j = 1:min(i, n_yes)
% Ensure we do not exceed the number of 'no' elements
if (i - j) <= n_no
% Generate all combinations of 'yes' and 'no' elements
yes_combinations = nchoosek(1:n_yes, j);
no_combinations = nchoosek(1:n_no, i - j);
% Initialize the sum for C_ij
sum_C_ij = 0;
% Loop through all combinations of 'yes' elements
for y_comb = 1:size(yes_combinations, 1)
% Loop through all combinations of 'no' elements
for n_comb = 1:size(no_combinations, 1)
% Calculate the product for the current combination
product = prod(yes(yes_combinations(y_comb, :))) * prod(no(no_combinations(n_comb, :)));
% Add the product to the sum for C_ij
sum_C_ij = sum_C_ij + product;
end
end
% Store the sum in the matrix C
C(i, j) = sum_C_ij;
end
end
end
% Display the matrix C
disp('Matrix C:');
disp(C);
0 个评论
另请参阅
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!