How to remove zero columns from array

后端 未结 4 1740
被撕碎了的回忆
被撕碎了的回忆 2020-12-12 00:01

I have an array which looks similar to:

 0     2     3     4     0     0     7     8     0    10
 0    32    44    47     0     0    37    54     0    36
         


        
4条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-12-12 00:12

    You had the right approach with x(x == 0) = [];. By doing this, you would remove the right amount of elements that can still form a 2D matrix and this actually gives you a vector of values that are non-zero. All you have to do is reshape the matrix back to its original form with 2 rows:

    x(x == 0) = [];
    y = reshape(x, 2, [])
    
    y =
    
         2     3     4     7     8    10
        32    44    47    37    54    36
    

    Another way is with any:

    y = x(:,any(x,1));
    

    In this case, we look for any columns that are non-zero and use these locations to index into x and extract out those corresponding columns.

    Result:

    y =
    
         2     3     4     7     8    10
        32    44    47    37    54    36
    

    Another way which is more for academic purposes is to use unique. Assuming that your matrix has all positive values:

    [~,~,id] = unique(x.', 'rows');
    y = x(:, id ~= 1)
    
    y =
    
         2     3     4     7     8    10
        32    44    47    37    54    36
    

    We transpose x so that each column becomes a row, and we look for all unique rows. The reason why the matrix needs to have all positive values is because the third output of unique assigns unique ID to each unique row in sorted order. Therefore, if we have all positive values, then a row of all zeroes would be assigned an ID of 1. Using this array, we search for IDs that were not assigned a value of 1, and use those to index into x to extract out the necessary columns.

提交回复
热议问题