MATLAB: Sum all possible combinations of tablecolumns

combinationMATLABsum table

I have a table with 30 columns. Now i would like create new tables for all possible summations of the table columns.
Like :
  • a table for all possible summations of 2 columns
  • a table for all possible summations of 3 colomns
  • a table for all possible summations of 4 colomns
Is there a way/ matlab function of combination of functions to realise this?

Best Answer

You can get all possible combinations of k columns choosen out of given n columns using nchoosek. REad about this function. You can get the sum of columns using sum. I have give a demo of calculating sum of two coumns with all possible combinations out of give columns. This can bve extended to any of your interested case.
A = rand(10,5) ; % matrix for demo
[m,n] = size(A) ; % get size of matrix
% Get possilbe combinations out of 5 columns when 2 columns are pciked
col = 1:n ;
idx = nchoosek(col,2) ;
% Add all combinations of two columns pciked from A
iwant = zeros(m,size(idx,1)) ; % initialize the required
for i = 1:size(idx,1)
iwant(:,i) = sum(A(:,idx(i,:)),2) ;
end