Removing the leading & trailing zeros from a vector Using MATLAB

This is what we need while we are developing in communication systems. These zeros could be used just to gather synchronization information or they may act as a start or end delimiter of the transmitted frame.
Thus to get the useful data back we need to remove all these padded zeros from the received frame, which could be visualized by a vector in MATLAB.

Removing both leading & trailing zeros from a vector Using MATLAB
Suppose we are having a vector like:
x=[0 0 0 -4 -2 0 -7 -8 0 0 0]
Clearly it has been padded by three zeros at the end & the starting.
But How to remove that? And that too specifically by using our Favorite software MATLAB!

So to get the vector as 4 -2 0 -7 -8 what we are going to do is type the below statement,

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

The above will remove all the leading & trailing zeros from the vector 'x' & store it in vector 'y'.
Result, 
y =

    -4    -2     0    -7    -8

Removing only leading zeros from a vector Using MATLAB
What if we just have padded only the leading zeros & trailing zeros are actually important bits of information, so we just need to remove the leading zeros from the vector 'x'.
How we are going to do it is simply like typing the following command,

y=x(find(x, 1, 'first'):end)

& will result in,
y =

    -4    -2     0    -7    -8     0     0     0

Removing only trailing zeros from a vector Using MATLAB
At last what if we want only the trailing zeros to be removed from the vector. Another simple single line MATLAB code for that will be,

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

& will result in
y =

     0     0     0    -4    -2     0    -7    -8

So, it was a simple stuff. More specifically it was a game of array indexing of/in MATLAB.
You just going some experience in MATLAB to get an idea of these small but beautiful tricks!




0 comments: