Removing columns in an array with zeros

I have an array starting at zeros and continuing into other numbers I would like to remove columns in an array that start at zero but keep other numbers

example column array below:

x = [0 0 0 0 0 2 4 6 8 0 1 2];

The column array response would look like

x = 2 4 6 8 0 1 2

I am using octave 3.4.2 / matlab

thank

+3


source to share


3 answers


Here is the code:

x = x(find(x~=0, 1):end);

      



or

x(1:find(x~=0,1)-1) = [];

      

+1


source


The find command should work for this.

Assuming your vector is x:



 find(x ~= 0)

      

Will return all indices where x is nonzero. Just take the first index and go from there to remove all values ​​from 1 to index.

+1


source


Logical indexing will work fine in this case: i.e.

y = x(:,x(1,:)~=0)

      

will do the job for you. An internal boolean comparison x(1,:)~=0

returns true for every column whose first element is non-zero. The indexing operation x(:,...)

selects only those columns for which a boolean comparison is returned.

+1


source







All Articles