sum all combinations of 2d array

7 次查看(过去 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.)

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