How to calculate sequencing arrays in a matrix
조회 수: 1 (최근 30일)
이전 댓글 표시
The matrix A has 2 columns: first is ID and second is the degree.
A = [2842198 7
2842198 7
2842198 2
2842198 7
2842198 7
2842198 6
2842198 1
2842443 7
2842443 7
2842443 8
2842443 4
2842443 6
2842463 7
2842463 9
2842463 7
2842463 6
2842463 5
2842463 7
2842463 7
2842463 6
2842463 3
2842463 10
2842463 3
2842463 6
];
I want to find the sequence matrix from matrix A like this (matrix B).
B = [0 0 0 0 0 0 1 0 0 0
0 0 0 0 0 0 1 0 0 0
0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0
1 0 0 0 0 0 0 0 0 0
0 1 0 1 0 1 2 0 0 0
0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0
];
Since there are 10 different degrees in matrix A, then the matrix B dimension is 10*10. For example, the first row in matrix B is referring to degree "1". If the second row of matrix A is "1", then B(1,1) should be 1, otherwise 0. In this example sice the second row of matrix A is 7, then B(1,7) = 7. This procedure should be repeated until ID changed in the matrix A.
Also, for each unique ID in matrix A, the sequence of last row should be compared with the first row of the same unique ID. For example here for ID 2842198, the last row degree is 1 and subsequently the first row of same unique ID is 7. So, result in matrix B(1,7) should be 1.
Finally, if there are sequence repeated more than 1, then result in matrix B should be summed up. For example, a sequence of 7 and 7 repeated 2 times, so result in B(7,7) is 2.
![](https://www.mathworks.com/matlabcentral/answers/uploaded_files/154206/image.jpeg)
댓글 수: 2
Guillaume
2016년 6월 20일
Why do you get values in B for row/column 4 when no degree 4 appear for ID 2842198?
채택된 답변
Guillaume
2016년 6월 20일
If I understood correctly, a simple accumarray is all you need:
ids = unique(A(:, 1));
numdegrees = max(A(:, 2));
out = cell(numel(ids), 2);
for idxid = 1:numel(ids)
Aid = A(A(:, 1) == ids(idxid), :);
out{idxid, 1} = ids(idxid);
out{idxid, 2} = accumarray([Aid(:, 2), Aid([2:end, 1], 2)], 1, [numdegrees, numdegrees]);
end
column 2 of the cell array is your B array for each unique ID (stored in column 1)
추가 답변 (0개)
참고 항목
카테고리
Help Center 및 File Exchange에서 Matrix Indexing에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!