Question

I have an array

x =

    404  1  1  5  5  1  1  5  0  0   0   0   0   0   0   0  0
    405  2  5  5  4  5  2  5  4  5   3   3   2   5   3   3  0
    406  5  5  3  5  3  5  4  3  3   1   4   0   0   0   0  0

I'd like to remove all the zeros EXCEPT the ones directly to the right of a non-zero integer. i.e. all but the last zero in a row of integers. (e.g., x=x(x~0); just removes zeros but then returns a column vector. So that's not quite right) Then concatenate all the the remaining vectors.

Like this:

404  1  1  5  5  1  1  5  0 405  2  5  5  4  5  2  5  4  5   3   3   2   5   3   3  0 406  5  5  3  5  3  5  4  3  3   0   4

Any ideas?

Was it helpful?

Solution

How about

x = x.';
dx = x ~= 0;
dx = dx | circshift(dx, 1)

y = x(dx).'

So, broken down:

  1. find the logical indices to the non-zeros to the transposed array
  2. circularly shift this array down by one and OR it with the original logicals, to get in the zeros directly after the non-zeros
  3. Index the array with these logicals and transpose to complete the operation
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top