Finding and removing leading/trailing zeros

### 21.2.2 Finding and removing leading/trailing zeros

You can find leading and/or trailing zeros in a vector and remove them by using the trim command (see Section 5.2.5, Section 28.1.9 and Section 28.2.2 for other usages of trim).

- trim takes one mandatory argument and up to three optional arguments:
  - v, a vector of real or complex numbers.
  - Optionally, threshold, a positive real number specifying the threshold for zeros (by default, threshold=epsilon(), the working precision).
  - Optionally, either left or right, the symbol specifiying one-sided trimming.
  - Optionally, index, the symbol.
- trim(v ⟨,threshold ⟩ ⟨,left|right ⟩ ⟨,index ⟩) finds the index l of the first nonzero element in v and the index u of the first trailing zero in v. A number z is considered to be zero if |z|≤threshold. If index is given, then the return value is either l if left is given, u if right is given, or (l,u−l) otherwise (the last sequence contains the start and length of the truncated vector). If index is omitted, then the return value is the portion of v between v[l] (inclusive) and v[u] (exclusive); if left is given, then u=length(v), and if right is given, then l=0.

#### Example

v:=[0,0,1e-16,0,-1e-13,1,2,3,0,0,0]:;

To remove leading zeros from v:

trim(v,left)

| ⎡ ⎣ | 1,2,3,0,0,0 | ⎤ ⎦

To remove leading and trailing zeros with threshold set to 10−14 (the default is the value of epsilon(), which is 10−12 in this case):

trim(v,1e-14)

| ⎡ ⎣ | −1.0×10−13,1,2,3 | ⎤ ⎦

To return the start and length of the nonzero part of v:

d,n:=trim(v,index)

5,3 |  |  |  |  |  |  |  |  |  |

Now, enter

mid(v,d,n)

to obtain the trimmed variant of v.