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:
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):
To return the start and length of the nonzero part of v:
Now, enter
to obtain the trimmed variant of v.