MATLAB - Remove Leading and Trailing Zeros From a Vector

I have a wavelet function with leading and trailing zeros. I would like to strip all the zeros which occur before or after the wavelet. However, I would not like to remove any zeros within the wavelet itself. To simplify, let's say I have the following 1x11 vector:

0 0 0 -2 -1 0 -1 -2 0 0 0

After removing leading and trailing zeros the vector should be:

-2 -1 0 -1 -2

My actual vectors are large and performance is my primary concern. I am a MATLAB novice and would appreciate any tips on how to accomplish this task as efficiently as possible.


Try this

 y = x(find(x,1,'first'):find(x,1,'last'));

The find(x,1,'option') command gives you first and last non-zero indices.

i1 = find(X, 1, 'first')

will give you the index of the first non-zero element of X

i2 = find(X, 1, 'last') 

will give you the index of the last one. Then


will give you the array with the leading and trailing zeros stripped.

Need Your Help

.net UrlEncode - lowercase problem

.net urlencode

I'm working on a data transfer for a gateway which requires me to send data in UrlEncoded form. However, .net's UrlEncode creates lowercase tags, and it breaks the transfer (Java creates uppercase)...

Vista or XP for Dev Machine

operating-system windows-xp windows-vista

I am about to get a new PC from work, and it will include the option to have either Vista Business as the OS, or a downgrade to XP Pro. Aside from a tiny bit of testing, I have never used Vista, but