MATLAB: How tp join multiple matrices in one matrix

arraycell arraysfor loopif statementMATLABmatrix manipulation

Assume matrix A1, A2 and A3 as follows:
A1 = [
1 10 23
2 12 45
3 23 43
4 32 45
5 32 32
];
A2 = [
1 43 10
2 56 11
3 34 24
4 43 65
];
A3 = [
1 32 12
2 22 21
];
I want to join all of these matrices into one matrix A according to the unique ID number (first column in every matrix). For example, all row with ID = 1 in all three matrices should written first, then all ID = 2, then all ID = 3, and so on.
A = [
1 10 23
1 43 10
1 32 12
2 12 45
2 56 11
2 22 21
3 23 43
3 34 24
4 32 45
4 43 65
];

Best Answer

Use the sortrows function on the vertically concatenated matrices:
A = sortrows([A1; A2; A3], 1)
A =
1 10 23
1 43 10
1 32 12
2 12 45
2 56 11
2 22 21
3 23 43
3 34 24
4 32 45
4 43 65
5 32 32
Experiment to get the result you want. To eliminate the last row, the assignment becomes:
A = A(1:end-1,:);
Related Question