Addition of certain consecutive elements along column in a matrix.
조회 수: 2 (최근 30일)
이전 댓글 표시
I have a matrix A, where only one '1' is present in a particular row.
A=[
0 0 0 0 1;
1 0 0 0 0;
1 0 0 0 0;
0 0 1 0 0;
0 0 0 0 1;
0 0 0 0 1;
0 0 0 0 1;
0 0 0 0 1;
0 0 1 0 0;
0 0 1 0 0;
0 0 0 0 1;
0 0 0 0 1]
Now I want to add all the consecutive '1' along columns whose out put will be B.
B[
0 0 0 0 1;
2 0 0 0 0;
0 0 1 0 0;
0 0 0 0 4;
0 0 2 0 0;
0 0 0 0 2]
댓글 수: 3
Jos (10584)
2018년 1월 11일
But why stores this in a matrix like B? Wouldn't your rather want the output to be like
5 1
1 2
3 1
5 4
3 2
5 2
Where the first column indicates the row where the sequence of 1's start, and the second column the number of 1's in the sequence? From this you can easily build the matrix B
채택된 답변
Guillaume
2018년 1월 11일
편집: Guillaume
2018년 1월 11일
This should do it:
A=[
0 0 0 0 1;
1 0 0 0 0;
1 0 0 0 0;
0 0 1 0 0;
0 0 0 0 1;
0 0 0 0 1;
0 0 0 0 1;
0 0 0 0 1;
0 0 1 0 0;
0 0 1 0 0;
0 0 0 0 1;
0 0 0 0 1];
assert(all(sum(A, 2)) == 1), 'A must have one and only one 1 per row');
transitions = diff([zeros(1, size(A, 2)); A; zeros(1, size(A, 2))]); %identify starts (1) and ends (-1) of sequences in each column
[transrow, transcol] = find(transitions); %get location.
%Note that since find works columnwise, transx(1:2:end) is the start of sequence, and transy(2:2:end) is the end
seqlengths = transrow(2:2:end) - transrow(1:2:end); %length of sequences
B = zeros(size(A));
B(sub2ind(size(B), transrow(1:2:end), transcol(1:2:end))) = seqlengths; %put sequence length at start locations
B(~any(B, 2), :) = [] %and remove empty rows
edit: I agree with Jos that storing the result as a two column matrix of columnnumber length would make more sense. That is easily obtained with:
C = [transcol(1:2:end, seqlengths];
[~, order] = sort(transrow(1:2:end));
C = C(order, :)
without needing to build B.
댓글 수: 0
추가 답변 (1개)
Jos (10584)
2018년 1월 11일
if ~all(sum(A,2)==1)
error('invalid input!')
end
Z = zeros(1,size(A,2))
dA = diff([Z ; A ; Z], 1, 1).'
[C,r1] = find(dA == 1)
[~,r2] = find(dA == -1)
N = r2 - r1
% C and N hold all the information you need to create B
B = zeros(numel(C), size(A,2))
idx = sub2ind(size(B), 1:size(B,1), C(:).')
B(idx) = N
참고 항목
카테고리
Help Center 및 File Exchange에서 Creating and Concatenating Matrices에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!