Search code examples
algorithmmatlabfinance

Matlab: sorting a matrix in a unique way


I have a problem with sorting some finance data based on firmnumbers. So given is a matrix that looks like:

[1 3 4 7;
1 2 7 8;
2 3 7 8;]

On Matlab i would like the matrix to be sorted as follows:

[1 0 3 4 7 0;
1 2 0 0 7 8;
0 2 3 0 7 8;]

So basically every column needs to consist of 1 type of number.

I have tried many things but i cant get the matrix sorted properly.


Solution

  • Answer without assumptions - Simplified

    I did not feel comfortable with my old answer that makes the assumption of everything being an integer and removed the possibility of duplicates, so I came up with a different solution based on @lib's suggestion of using a histogram and counting method.

    The only case I can see this not working for is if a 0 is entered. you will end up with a column of all zeros, which one might interpret as all rows initially containing a zero, but that would be incorrect. you could uses nan instead of zeros in that case, but not sure what this data is being put into, and if it that processing would freak out.

    EDITED

    Includes sorting of secondary matrix, B, along with A.

    A = [-1 3 4 7 9; 0 2 2 7 8.2; 2 3 5 9 8];
    B = [5 4 3 2 1; 1 2 3 4 5; 10 9 8 7 6];
    
    keys = unique(A);
    [counts,bin] = histc(A,transpose(unique(A)),2);
    A_sorted = cell(size(A,1),1);
    for ii = 1:size(A,1)
        for jj = 1:numel(keys)
            temp = zeros(1,max(counts(:,jj)));
            temp(1:counts(ii,jj)) = keys(jj);
            A_sorted{ii} = [A_sorted{ii},temp];
        end
    end
    
    A_sorted = cell2mat(A_sorted);
    B_sorted = nan(size(A_sorted));
    for ii = 1:size(bin,1)
       for jj = 1:size(bin,2)
           idx = bin(ii,jj);
           while ~isnan(B_sorted(ii,idx))
              idx = idx+1; 
           end
           B_sorted(ii,idx) = B(ii,jj);
       end
    end
    B_sorted(isnan(B_sorted)) = 0