tags:

views:

90

answers:

2

I have a vector for example

a = [0 1 0 3]

I want to turn a into b which equals b = [1 3]

How do I perform this in general? So I have a vector with some zero components and I want to remove the zeroes and leave just the non-zero numbers.

Sorry I am new to Matlab

+1  A: 
b = a(find(a~=0))
High Performance Mark
just `b = a(find(a))` is sufficient, the default is to find nonzero values.
wich
or `b = a(a~=0)` is sufficient, logical indexing is implied.
mtrw
Good comments, I feel bad getting my poor answer upvoted.
High Performance Mark
+12  A: 

If you just wish to remove the zeros, leaving the non-zeros behind in a, then the very best solution is

a(a==0) = [];

This deletes the zero elements, using a logical indexing approach in MATLAB. When the index to a vector is a boolean vector of the same length as the vector, then MATLAB can use that boolean result to index it with. So this is equivalent to

a(find(a==0)) = [];

And, when you set some array elements to [] in MATLAB, the convention is to delete them.

If you want to put the zeros into a new result b, while leaving a unchanged, the best way is probably

b = a(a ~= 0);

Again, logical indexing is used here. You could have used the equivalent version (in terms of the result) of

b = a(find(a ~= 0));

but mlint will end up flagging the line as one where the purely logical index was more efficient, and thus more appropriate.

As always, beware EXACT tests for zero or for any number, if you would have accepted elements of a that were within some epsilonic tolerance of zero. Do those tests like this

b = a(abs(a) >= tol);

This retains only those elements of a that are at least as large as your tolerance.

woodchips
or for the first example, `a = a(a~=0)` is sufficient, the in-place assignment works fine. Good point on testing against a small number rather than 0.
mtrw

related questions