MATLAB: Creating a matrix by sorting the colums of another matrix

columnrowsort

0 4;
5 3;
1 3;
0 5;
0 1
I have a matrix like this. Its size is 3×2 but it can be nx2. I want to sort it like that; [0 4; 0 1 3;0 5 3]. What i mean by that is the code should create row which starts from 0 and follows the next number. If the next number is stored also in the first column then the row should take the next next number and so on. How can i write the code? Thx

Best Answer

m = [0 4; 5 3; 1 3; 0 5; 0 1]; %demo data
startrows = find(m(:, 1) == 0);
out = cell(numel(startrows), 1); %can't use a matrix because of the different number of elements per row
for row = 1:numel(startrows)
out{row} = m(startrows(row), :);
nextrow = find(m(:, 1) == m(startrows(row), 2));
while ~isempty(nextrow)
assert(numel(nextrow) == 1, 'More than one row matched current number: %d', m(nextrow, 1));
out{row} = [out{row}, m(nextrow, 2)];
nextrow = find(m(:, 1) == m(nextrow, 2));
end
end