How to remove zero columns from array

后端 未结 4 1729
被撕碎了的回忆
被撕碎了的回忆 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条回答
  • 2020-12-12 00:11

    You could also use sum. Sum over the columns and any column with zeros only will be zeros after the summation as well.

    sum(x,1)
    ans =
    
        0   34   47   51    0    0   44   62    0   46
    

    x(:,sum(x,1)>0)
    
    ans =
    
        2    3    4    7    8   10
       32   44   47   37   54   36
    
    0 讨论(0)
  • 2020-12-12 00:11

    Also by reshaping nonzeros(x) as follows:

    reshape(nonzeros(x), size(x,1), [])
    
    ans =
    
         2     3     4     7     8    10
        32    44    47    37    54    36
    
    0 讨论(0)
  • 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.

    0 讨论(0)
  • 2020-12-12 00:33

    Here is a possible solution:

    x(:,all(x==0))=[]
    
    0 讨论(0)
提交回复
热议问题