General Stubbs
General Stubbs

Reputation: 173

How to remove zero columns from array

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

I wish to remove all

0
0

from this to get:

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

I've tried x(x == 0) = [] but I get:

x =

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

How can I remove all zero columns?

Upvotes: 3

Views: 3957

Answers (4)

AboAmmar
AboAmmar

Reputation: 5559

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

Upvotes: 0

rayryeng
rayryeng

Reputation: 104474

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.

Upvotes: 3

kkuilla
kkuilla

Reputation: 2256

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

Upvotes: 1

vsoftco
vsoftco

Reputation: 56547

Here is a possible solution:

x(:,all(x==0))=[]

Upvotes: 4

Related Questions