Search code examples
matlabsortingadjacency-matrix

Remove a proportion of values in an adjacency matrix


I have a 6x6 adjacency matrix M. I want to work with only all the values 1 below the diagonal line (i.e.,tril(M,-1)). With the remaining values, I want to binarize the matrix such that the top 20% of values are converted to 1 and the lower 80% are converted to zeros. M is something like this:

-0.01   0.09    -0.16   -0.11   0.29    0.11
0.09    0.00    0.09    0.09    0.48    0.44
-0.16   0.09    0.01    -0.09   0.09    0.14
-0.11   0.09    -0.09   -0.01   -0.18   -0.04
0.29    0.48    0.09    -0.18   0.00    0.05
0.11    0.44    0.14    -0.04   0.05    0.00

Output would be:

0.00    0.00    0.00    0.00    0.00    0.00
0.00    0.00    0.00    0.00    0.00    0.00
0.00    0.00    0.00    0.00    0.00    0.00
0.00    0.00    0.00    0.00    0.00    0.00
0.29    0.48    0.00    0.00    0.00    0.00
0.00    0.44    0.00    0.00    0.00    0.00

I was thinking I could sort all the values below the diagonal line then only pick the 20% but I'm not sure how to sort the entire matrix (as opposed to sorting a single column/row). Could anyone help?

Edit: I guess I could reshape M then sort it but that doesn't seem to be efficient. I would love to see a better approach.


Solution

  • You can try the following approach:

    trilMask = logical(tril(ones(size(M)),-1)); %generates trilMask
    M(~trilMask ) = 0; %zero-out values outsideMask
    relevantVals = sort(M(trilMask)); %sort values
    T = relevantVals(round(length(relevantVals )*0.8)+1); %calc threshold,
    M(M<T) = 0 %perform thresholding
    

    Result:

    M =
    
         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.2900    0.4800         0         0         0         0
         0    0.4400         0         0         0         0