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!