how to add column of a matrix

1 次查看(过去 30 天)
Monika  Kok
Monika Kok 2016-4-25
a= [1 2 3 4 ; 1 0 1 6; 4 5 6 7; 1 0 3 3]
a(:,1) = a(:,1)+a(:,2);
i am using the above code but i would like to generate a for loop which will give me addition of column such as:
1)column 1 + column 2
2)[column1+column3] and [column1+column2+column3]
3)[column1+column4] and [column1+column2+column4] and [column1+column3+column4] and [column1+column2+column3+column4]
so taking first and last column and getting all the possible combination between them
thanks monica

回答(1 个)

Roger Stafford
Roger Stafford 2016-4-25
b = zeros(4,16);
for k = 0:15
t = double(dec2bin(k,4)-'0');
b(:,k+1) = sum(bsxfun(@times,a,t),2);
end
The sixteen columns of b give sums of all possible subsets of columns of a (including the empty set.)
  2 个评论
Monika  Kok
Monika Kok 2016-4-27
the thing which i want is lets say if i am using using column 1 and column 3 then they should be in every combination. only the column between them should provide a combination
Walter Roberson
Walter Roberson 2016-4-27
FirstCol = 1; LastCol = 4;
colspan = LastCol - FirstCol - 1;
num_arrange = 2^colspan;
num_row = size(a,1);
num_col = size(a,2);
b = zeros(num_row, num_arrange);
for k = 0 : num_arrange - 1
t = [zeros(1, FirstCol-1), 1, fliplr(double(dec2bin(k,colspan)-'0')), 1, zeros(1, num_col - LastCol)];
b(:,k+1) = sum(bsxfun(@times,a,t),2);
end

请先登录,再进行评论。

类别

Help CenterFile Exchange 中查找有关 Matrices and Arrays 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by