sum all combinations of 2d array

조회 수: 5 (최근 30일)
Alex
Alex 2011년 10월 27일
답변: Jos (10584) 2017년 11월 29일
So I have an array
a = [1,2,3,4;5,6,7,8;9,10,11,12;13,14,15,16];
now i want to sum every combination. Like a number padlock, i.e
value1 = a(1,1)+a(2,1)+a(3,1)+a(4,1);
value2 = a(1,1)+a(2,1)+a(3,1)+a(4,2);
value3 = a(1,1)+a(2,1)+a(3,1)+a(4,3);
value4 = a(1,1)+a(2,1)+a(3,1)+a(4,4);
value5 = a(1,1)+a(2,1)+a(3,2)+a(4,1);
value6 = a(1,1)+a(2,1)+a(3,2)+a(4,2);
value7 = a(1,1)+a(2,1)+a(3,2)+a(4,3);
value8 = a(1,1)+a(2,1)+a(3,2)+a(4,4);
value9 = a(1,1)+a(2,1)+a(3,3)+a(4,1);
value10 = a(1,1)+a(2,1)+a(3,3)+a(4,2);
value11 = a(1,1)+a(2,1)+a(3,3)+a(4,3);
value12 = a(1,1)+a(2,1)+a(3,3)+a(4,4);
etc etc etc
except I cant figure out the for loops. Espscially with the fact that the array size can change, so I cant just statically place for loops inside of each other, because i dont necessarily know how many rows/columns there will be? Has anyone done anything like this? Thanks
  댓글 수: 4
Fangjun Jiang
Fangjun Jiang 2011년 10월 27일
Are these all the combination or just a sample of examples? What is the logic for picking the numbers? one number from each row (or column)?
Franc Lever
Franc Lever 2017년 11월 29일
편집: Franc Lever 2017년 11월 29일
Like This, and in C you cna input any operation or function you wish
a=[1 2 3 4 5];
b=[1 2 3 5 6];
[A,B]=meshgrid(a,b);
C=A+B
C =
2 3 4 5 6
3 4 5 6 7
4 5 6 7 8
6 7 8 9 10
7 8 9 10 11

댓글을 달려면 로그인하십시오.

답변 (3개)

Walter Roberson
Walter Roberson 2011년 10월 27일
by_row = mat2cell(a,ones(1,size(a,1)),size(a,2));
d = numel(by_row);
combos = cell(1,d);
[combos{:}] = ndgrid(by_row{:});
values = sum(cat(d+1,combos{:}),d+1);
The result of this will be that values will be an array, each dimension of which is the number of columns in a, with the number of dimensions being the same as the number of rows in a.
For example, a=rand(3,4) would give a 4 x 4 x 4 result.
(I'll have to recheck whether this is the desirable output size when I have a bit more time.)
  댓글 수: 1
Andrei Bobrov
Andrei Bobrov 2011년 10월 28일
values = sum(cat(d+1,combos{:}),d+1);
values = values(:);

댓글을 달려면 로그인하십시오.


Jos (10584)
Jos (10584) 2017년 11월 29일
a = [1,2,3,4; 5,6,7,8; 9,10,11,12; 13,14,15,16]; % data
[n,m] = size(a) ;
c = permn(1:m, n) ; % get all permutations of the column indices
r = repmat(1:n, size(c,1), 1) ; % create matching row indices
i = sub2ind([n m], r) ; % transform row and column subindices into linear indices
values = sum(a(i), 2) ; % sum rows to get the required values

Jos (10584)
Jos (10584) 2017년 11월 29일
And another, faster, solution:
a = [1,2,3,4; 5,6,7,8; 9,10,11,12; 13,14,15,16]; % data
c = mat2cell(a,size(a,1),ones(1,size(a,2)))
values = sum(allcomb(c{:}),2) ;
The function ALLCOMB can be downloaded from the File Exchange:

카테고리

Help CenterFile Exchange에서 Creating and Concatenating Matrices에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by