How to use the index of a matrix in another one?
정보
이 질문은 마감되었습니다. 편집하거나 답변을 올리려면 질문을 다시 여십시오.
이전 댓글 표시
EDIT
I have a matrix y(k,sum(counter))=
0 1 0 0 1 0
1 0 0 1 0 0
0 1 0 0 1 0
1 0 0 1 0 0
0 1 0 0 1 0
counter(j,1) =
[ 2
1
3 ]
I want something that says for each j in the counter(j,1) find its value, then sum the columns of y that are equal to the value in the counter.
for counter (1)= 2 , then sum the first (two) columns in y
for counter(2)= 1 , sum the following (one) column ( will stay the same basically)
for counter(3) = 3, sum the following (three) columns in y
y_new = [
1 0 1
1 0 1
1 0 1
1 0 1
1 0 1 ]
댓글 수: 2
Azzi Abdelmalek
2013년 12월 1일
This is not clear, what is counter? , what does mean (which is equal 2)?
Islam
2013년 12월 1일
답변 (3개)
Wayne King
2013년 12월 1일
You are missing something in your description, summing the first two columns of y does not result in y_new. How did you get a third column of all ones in y_new?
idx = find(counter==1,1,'first');
B = A;
B(:,1) = sum(A(:,1:2),2);
B(:,2) = [];
The above creates a new matrix B with the first column equal to sum of the first two columns of A. But again what you described does not result in y_new
댓글 수: 1
Islam
2013년 12월 1일
Azzi Abdelmalek
2013년 12월 2일
y=[ 0 1 0 1 1 0
1 0 0 1 0 0
0 1 0 0 1 0
1 0 0 1 0 0
0 1 0 0 1 0]
counter =[2;1;3];
ii=1;
idx1=1;
for k=counter'
idx2=idx1+k-1;
out(:,ii)=sum(y(:,idx1:idx2),2);
idx1=idx2+1;
ii=ii+1;
end
out
댓글 수: 0
Andrei Bobrov
2013년 12월 2일
편집: Andrei Bobrov
2013년 12월 2일
iend = cumsum(counter);
ifs = iend - counter + 1;
idx = zeros(iend(end),1);
idx(ifs) = 1;
idx = cumsum(idx);
[ii,jj] = ndgrid(1:size(y,1;),idx);
out = accumarray([ii(:),jj(:)],y(:));
or
out = cell2mat(cellfun(@(x)sum(x,2),mat2cell(y,size(y,1),counter),'un',0));
or
i0 = cumsum(counter);
i1 = i0 - counter + 1;
for ii = numel(counter):-1:1
out(:,ii) = sum(y(:,i1(ii):i0(ii)),2);
end
댓글 수: 0
이 질문은 마감되었습니다.
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!