how to add column of a matrix

조회 수: 2 (최근 30일)
Monika  Kok
Monika Kok 2016년 4월 25일
댓글: Walter Roberson 2016년 4월 27일
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