how to add column of a matrix
2 次查看(过去 30 天)
显示 更早的评论
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
0 个评论
回答(1 个)
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 个评论
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 Center 和 File Exchange 中查找有关 Matrices and Arrays 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!