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