Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 502
nedblorf Avatar asked Mar 30 '11 15:03

nedblorf


People also ask

How do you remove leading zeros from an array?

Approach: Mark the first non-zero number's index in the given array. Store the numbers from that index to the end in a different array. Print the array once all numbers have been stored in a different container.

How do you get rid of trailing zeros?

Multiply by 1. A better way to remove trailing zeros is to multiply by 1 . This method will remove trailing zeros from the decimal part of the number, accounting for non-zero digits after the decimal point. The only downside is that the result is a numeric value, so it has to be converted back to a string.

How do you trim a string in Matlab?

Description. newStr = strip( str ) removes all consecutive whitespace characters from the beginning and end of str , and returns the result as newStr . newStr = strip( str , side ) removes all consecutive whitespace characters from the side specified by side . The side argument can be 'left' , 'right' , or 'both' .


2 Answers

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.

like image 154
Phonon Avatar answered Oct 19 '22 13:10

Phonon


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

X(i1:i2)

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

like image 20
Dima Avatar answered Oct 19 '22 12:10

Dima