How to calculate sequencing arrays in a matrix

2 views (last 30 days)
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.
  2 Comments
Guillaume
Guillaume on 20 Jun 2016
Why do you get values in B for row/column 4 when no degree 4 appear for ID 2842198?
Moe
Moe on 20 Jun 2016
Thanks Guillaume for notice it. Yes, in the above matrix B(4,6) should be 0.

Sign in to comment.

Accepted Answer

Guillaume
Guillaume on 20 Jun 2016
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)
  2 Comments
Moe
Moe on 20 Jun 2016
Edited: Moe on 20 Jun 2016
Thanks Guillaume. Is there a way to aggregate all of "out" into one matrix?
Guillaume
Guillaume on 20 Jun 2016
Edited: Guillaume on 20 Jun 2016
vertcat(out{:, 2})
%or
cell2mat(out(:, 2})
In my opinion, a lot less useful than keeping them separate.

Sign in to comment.

More Answers (0)

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!