Search code examples
matlabsparse-matrix

best way to get a vector from sparse matrix


I have a m x n matrix where each row consists of zeros and same values for each row.

an example would be:

M = [-0.6 1.8 -2.3 0 0 0; 0 0 0 3.4 -3.8 -4.3; -0.6 0 0 3.4 0 0]

In this example the first column consists of 0s and -0.6, second 0 and 1.8, third -2.3 and so on.

In such case I would like to reduce m to 1 (get a vector from a given matrix) so in this example a vector would be [-0.6 1.8 -2.3 3.4 -3.8 -4.3]

Does anyone know what is the best way to get a vector from such matrix?

Thank you!


Solution

  • Here's a one-liner that uses the function SUM:

    nonZeroColumnValues = sum(M)./sum(M ~= 0);
    

    This will return a 1-by-n vector that contains the repeated non-zero value from each column. It does so by summing each column, then dividing the result by the number of non-zero values in each column. If there are no non-zero values in a column, the result for that column will be NaN.

    Here's an example using the sample matrix M in the question:

    >> M = [-0.6 1.8 -2.3 0 0 0; 0 0 0 3.4 -3.8 -4.3; -0.6 0 0 3.4 0 0]
    
    M =
    
       -0.6000    1.8000   -2.3000         0         0         0
             0         0         0    3.4000   -3.8000   -4.3000
       -0.6000         0         0    3.4000         0         0
    
    >> nonZeroColumnValues = sum(M)./sum(M ~= 0)
    
    nonZeroColumnValues =
    
       -0.6000    1.8000   -2.3000    3.4000   -3.8000   -4.3000