combination and their sum

1 次查看(过去 30 天)
sampath kumar punna
sampath kumar punna 2019-10-18
编辑: Bruno Luong 2019-10-19
hi can you help me with this
4 2
5 7
3 1
Combination 1: 4,5,3
Combination 2: 4,5,1
Combination 3: 4,7,3
Combination 4:2,5,3
Combination 6: 2,7,1
Combination 7: 2,7,3
Combination 8: 2,5,1
Combination 9: 4,7,1
And sum of each combination
thanks

回答(2 个)

the cyclist
the cyclist 2019-10-18
A = [4 2;
5 7;
3 1];
m = size(A,1);
output = [];
for j = 1:2
output = [output; A(:,j)'];
for i = 1:m
output = [output; [A(1:i-1,j); A(i,3-j); A(i+1:end,j)]'];
end
end
sumOutput = sum(output,2)
This will work for any number of rows, but only for 2 columns.
  1 个评论
sampath kumar punna
sampath kumar punna 2019-10-19
A = [1 2;
1 2;
1 2
1 2];
m = size(A,1);
output = [];
for j = 1:2
output = [output; A(:,j)'];
for i = 1:m
output = [output; [A(1:i-1,j); A(i,3-j); A(i+1:end,j)]'];
end
end
sum=output
sumOutput = sum(output,2)
if you could run this code you can see
this code is missing few combinations like
1 1 2 2
1 2 1 2
1 2 2 1
2 2 1 1
2 1 2 1
2 1 1 2
took 1 and 2 digits to understand combinations clearly.
Is it possible to fix the above error?
Can I get a code for n rows and n columns?

请先登录,再进行评论。


Bruno Luong
Bruno Luong 2019-10-19
编辑:Bruno Luong 2019-10-19
A = [4 2;
5 7;
3 1]
m = size(A,1);
b = dec2bin(0:2^m-1,m)-'0';
C = A((1:m)+m*b).'
Result (each column is a combination)
C =
4 4 4 4 2 2 2 2
5 5 7 7 5 5 7 7
3 1 3 1 3 1 3 1
Nest you can sum C by
>> sum(C)
ans =
12 10 14 12 10 8 12 10

类别

Help CenterFile Exchange 中查找有关 Logical 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by