OptiVec Logo 

VectorLib  



Site Index:

OptiVec home
MatrixLib
CMATH
Download
Order
Update
Support

VectorLib


4. VectorLib Functions and Routines: A Short Overview

4.1 Generation, Initialization and De-Allocation of Vectors
4.2 Index-oriented Manipulations
4.3 Data-Type Interconversions
4.4 More about Integer Arithmetics
4.5 Basic Functions of Complex Vectors
4.6 Mathematical Functions
4.6.1 Rounding
4.6.2 Comparisons
4.6.3 Direct Bit-Manipulation
4.6.4 Basic Arithmetics, Accumulations
4.6.5 Geometrical Vector Arithmetics
4.6.6 Powers
4.6.7 Exponentials and Hyperbolic Functions
4.6.8 Logarithms
4.6.9 Trigonometric Functions
4.7 Analysis
4.8 Signal Processing: Fourier Transforms and Related Topics
4.9 Statistical Functions and Building Blocks
4.10 Data Fitting
4.11 Input and Output
4.12 Graphics

4.1 Generation, Initialization and De-Allocation of Vectors


With VectorLib, you may use static arrays (like, for example, float a[100];) as well as dynamically allocated ones (see chapter 2.3). We recommend, however, that you use the more flexible vector types defined by VectorLib, using dynamic allocation.

The following functions manage dynamically allocated vectors: 

VF_vectormemory allocation for one vector
VF_vector0memory allocation and initialization of all elements with 0
V_freefree one vector
V_nfree free n vectors (only for C, not for Pascal)
V_freeAllfree all existing vectors
 
You should always take proper care to de-allocate the memory of vectors which are no longer needed. Internally, the allocated vectors are written into a table to keep track of the allocated memory. If you try to free a vector that has never been or is no longer allocated, you get a warning message, and nothing is freed.

Performance tips:

  • The vectors allocated by VF_vector etc. are aligned on 64 byte boundaries for optimum cache-line matching (Intel Pentium XX: 32 byte, AMD Athlon and all 64-bit processors by AMD and Intel: 64 byte). On the other hand, static arrays as well as vectors created by the operator new or by the standard functions, malloc, calloc, GetMem, LocalAlloc, GlobalAlloc etc. are aligned on 4 byte boundaries only. Consequently, for optimum performance, you should use only vectors allocated by VF_vector etc.
  • The SIMD commands employed in the P6 and P7 versions require data to be aligned on 16 byte boundaries. Again the same advice holds: Use the dynamic vectors of OptiVec to guarantee the necessary alignment. The penalty for not properly aligned data may amount to 25%.
  • Instead of many small vectors, consider allocating one large vector. Define the small vectors as parts of the larger one:
    C/C++:
    X = VF_vector( 3*size);
    Z = (Y = X+size) + size;
    Pascal/Delphi:
    X := VF_vector( 3*size );
    Y := VF_Pelement( X, size );
    Z := VF_Pelement( Y, size );
    Be sure size is rounded up so as to make size*sizeof( data type ) a multiple of 32 or 64.
  • Avoid frequent allocation and deallocation. Try to re-use vectors instead.

The following functions are used to initialize or re-initialize vectors that have already been created: 

VF_equ0set all elements of a vector equal to 0
VF_equ1set all elements equal to 1
VF_equm1set all elements equal to -1
VF_equCset all elements equal to a constant C
VF_equVmake one vector a copy of another
VFx_equV"expanded" version of the equality operation: Yi = a * Xi + b
VF_ramp"ramp": Xi = a * i + b.
VF_randomhigh-quality random numbers
VF_noisewhite noise
VF_comb"comb": equals a constant C at equidistant points, elsewhere 0
 

The following functions are used to access and modify single vector elements: 

VF_Pelementreturns a pointer to the vector element specified by its index
VF_elementreturns a specific vector element
VF_getElementcopies a specific vector element into a variable
VF_setElementsets a vector element to a new value
VF_accElementX[i] += c; adds a value to one vector element
VF_decElementX[i] -= c; subtracts a value from one vector element
 
The following functions generate windows for use in spectral analysis: 
VF_HannHann window
VF_ParzenParzen window
VF_WelchWelch window
 
Complex vectors may be initialized by these functions: 
VF_ReImtoCmerge two vectors, Re and Im, into one cartesian complex vector
VF_RetoCoverwrite the real part of a cartesian complex vector
VF_ImtoCoverwrite the imaginary part of a cartesian complex vector
VF_PolartoCconstruct a cartesian complex vector from polar coordinates, entered as separate vectors Mag and Arg
VF_MagArgtoPmerge two vectors, Mag and Arg into one polar complex vector
VF_MagArgtoPrincipalmerge two vectors, Mag and Arg into one polar complex vector, reducing the Arg range to the principal value, -p < Arg <= +p
VF_MagtoPoverwrite the Mag part of a polar complex vector
VF_ArgtoPoverwrite the Arg part of a polar complex vector
VF_ReImtoPconstruct a polar complex vector from cartesian coordinates, entered as separate vectors Re and Im

Back to VectorLib Table of Contents   OptiVec home 

4.2 Index-oriented Manipulations

VF_revreverse the element ordering
VCF_revconjcomplex conjugate in reverse element ordering
VF_reflectset the upper half of a vector equal to the reversed lower half
VF_rotaterotate the ordering of the elements
VF_rotate_bufefficient rotation, employing user-specified buffer memory
VF_insertinsert one element into a vector
VF_deletedelete one element from a vector
VF_sortfast sorting of the elements (ascending or descending order)
VF_sortindsorting of an index array associated with a vector
VF_subvectorextract a subvector from a (normally larger) vector, using a constant sampling interval.
VF_indpickfills a vector with elements "picked" from another vector according to their indices.
VF_indputdistribute the elements of one vector to the sites of another vector specified by their indices.
 
Operations performed only on a sampled sub-set of elements of a vector are provided by the VF_subvector_... family, where the omission mark stands for a suffix denoting the desired operation: 
VF_subvector_equC Xi*samp = C,   i=0,...subsize-1
VF_subvector_addC Xi*samp += C,   i=0,...subsize-1
VF_subvector_subC Xi*samp -= C,   i=0,...subsize-1
VF_subvector_subrC Xi*samp = C - Xi*samp,   i=0,...subsize-1
VF_subvector_mulC Xi*samp *= C,   i=0,...subsize-1
VF_subvector_divC Xi*samp /= C,   i=0,...subsize-1
VF_subvector_divrC Xi*samp = C / Xi*samp,   i=0,...subsize-1
VF_subvector_equV Yi*samp = Yi,   i=0,...subsize-1
VF_subvector_addV Xi*samp += Yi,   i=0,...subsize-1
VF_subvector_subV Xi*samp -= Yi,   i=0,...subsize-1
VF_subvector_subrV Xi*samp = Yi - Xi*samp,   i=0,...subsize-1
VF_subvector_mulV Xi*samp *= Yi,   i=0,...subsize-1
VF_subvector_divV Xi*samp /= Yi,   i=0,...subsize-1
VF_subvector_divrV Xi*samp = Yi / Xi*samp,   i=0,...subsize-1
 
Searching tables for specific values is accomplished by:
VF_searchC search for the element of a vector that is closest to a pre-set value C (closest, closest larger-or-equal, or closest smaller-or-equal value, depending on a parameter "mode")
VF_searchVthe same, but for a whole array of pre-set values
 
Interpolations are performed by: 
VF_polyinterpolpolynomial interpolation
VF_ratinterpolrational interpolation
VF_natCubSplineInterpolnatural cubic spline interpolation
VF_splineinterpolgeneral cubic spline interpolation
 

Back to VectorLib Table of Contents   OptiVec home 

4.3 Data-Type Interconversions

The first thing that has to be said about the floating-point data-type interconversions is: do not use them too extensively. Decide which accuracy is appropriate for your application, and then use consistently either the VF_, or the VD_, or the VE_ version of the functions you need. Nevertheless, every data type can be converted into every other, in case it is necessary. Only a few examples are given; the rest should be obvious: 
V_FtoDfloat to double
V_CDtoCFcomplex<double> to complex<float> (with overflow protection)
V_PFtoPEpolar<float> to polar<extended>
VF_PtoCpolar<float> to complex<float>
V_ItoLIint to long int
V_ULtoUSunsigned long to unsigned short
V_ItoUsigned int to unsigned int. Interconversions between signed and unsigned types can only be performed on the same level of accuracy. Functions like "V_UStoLI" do not exist.
V_ItoFint to float
 
The conversion of floating-point numbers into integers is performed by the following functions, differing in the way a possible fractional part is treated: 
VF_roundtoIround to the closest integer
VF_choptoIround by neglecting ("chopping off") the fractional part
VF_trunctoIthe same as VF_choptoI
VF_ceiltoIround to the next greater-or-equal integer
VF_floortoIround to the next smaller-or-equal integer
 
These operations are treated as mathematical functions and are further described in chapter 4.6.1.

Back to VectorLib Table of Contents   OptiVec home 

4.4 More about Integer Arithmetics

Although the rules of integer arithmetics are quite straightforward, it appears appropriate to recall that all integer operations are implicitly performed modulo 2n, where n is the number of bits the numbers are represented with. This means that any result, falling outside the range of the respective data type, is made to fall inside the range by loosing the highest bits. The effect is the same as if as many times 2n had been added to (or subtracted from) the "correct" result as necessary to reach the legal range.
For example, in the data type short / SmallInt, the result of the multiplication 5 * 20000 is -31072. The reason for this seemingly wrong negative result is that the "correct" result, 100000, falls outside the range of short numbers which is -32768 <= x <= +32767. short / SmallInt is a 16-bit type, so n = 16, and 2n = 65536. In order to make the result fall into the specified range, the processor "subtracts" 2 * 65536 = 131072 from 100000, yielding -31072.
Note that overflowing intermediate results cannot be "cured" by any following operation. For example, (5 * 20000) / 4 is not (as one might hope) 25000, but rather -7768.

Back to VectorLib Table of Contents   OptiVec home 

4.5 Basic Functions of Complex Vectors

The following functions are available for the basic treatment of cartesian complex vectors: 
VF_ReImtoCform a cartesian complex vector out of its real and imaginary parts
VF_RetoCoverwrite the real part
VF_ImtoCoverwrite the imaginary part
VF_CtoReImextract the real and imaginary parts
VF_CtoReextract the real part
VF_CtoImextract the imaginary part
VF_PolartoCform a cartesian complex vector out of polar coordinates, entered as separate vectors Mag and Arg
VF_CtoPolartransform cartesian complex into polar coordinates, returned in the separate vectors Mag and Arg
VF_CtoAbsabsolute value (magnitude of the pointer in the complex plane)
VF_CtoArgargument (angle of the pointer in the complex plane)
VF_CtoNormnorm (here defined as the square of the absolute value)
 
The corresponding functions for polar coordinates are:
VF_MagArgtoPmerge two vectors, Mag and Arg into one polar complex vector
VF_MagArgtoPrincipalmerge two vectors, Mag and Arg into one polar complex vector, reducing the Arg range to the principal value, -p < Arg <= +p
VF_MagtoPoverwrite the Mag part of a polar complex vector
VF_ArgtoPoverwrite the Arg part of a polar complex vector
VF_PtoMagArgextract the Mag and Arg parts
VF_PtoMagextract the Mag part
VF_PtoArgextract the Arg part
VF_PtoNormnorm (here defined as the square of the magnitude)
VF_ReImtoPconstruct a polar complex vector from cartesian coordinates, entered as separate vectors Re and Im
VF_PtoReImtransform a polar complex vector into two real vectors, representing the corresponding cartesian coordinates Re and Im
VF_PtoRecalculate the real part of the polar complex input numbers
VF_PtoImcalculate the imaginary part of the polar complex input numbers
VPF_principalcalculate the principal value. You might recall that each complex number has an infinite number of representations in polar coordinates, with the angles differing by an integer multiple of 2 p. The representation with -p < Arg <= +p is called the principal value.
 

Back to VectorLib Table of Contents   OptiVec home 

4.6 Mathematical Functions

Lacking a more well-founded definition, we denote as "mathematical" all those functions which calculate each single element of a vector from the corresponding element of another vector by a more or less simple mathematical formula:
Yi = f( Xi ).
Except for the "basic arithmetics" functions, they are defined only for the floating-point data types. Most of these mathematical functions are vectorized versions of scalar ANSI C or Pascal functions or derived from them. In C/C++, errors are handled by _matherr and _matherrl. In Pascal/Delphi, OptiVec allows the user to control error handling by means of the function V_setFPErrorHandling.

In addition to this error handling "by element", the return values of the VectorLib math functions show if all elements have been processed successfully. In C/C++, the return value is of the data-type int, in Pascal/Delphi, it is IntBool. (We do not yet use the newly introduced data type bool for this return value in C/C++, in order to make VectorLib compatible also with older versions of C compilers.) If a math function worked error-free, the return value is FALSE (0), otherwise it is TRUE (any non-zero number).

Back to VectorLib Table of Contents   OptiVec home 

4.6.1 Rounding

Some of the functions converting floating-point into integer vectors have already been noted above. The result of these rounding operations may either be left in the original floating-point format, or it may be converted into one of the integer types. The following functions store the result in the original floating-point format: 
VF_roundround to the closest integer
VF_chopround by neglecting ("chopping off") the fractional part
VF_truncthe same as VF_chop
VF_ceilround to the next greater-or-equal integer
VF_floorround to the next smaller-or-equal integer
 
The following functions store the result as integers (type int): 
VF_roundtoIround to the closest integer
VF_choptoIround by neglecting ("chopping off") the fractional part
VF_trunctoIthe same as VF_choptoI
VF_ceiltoIround to the next greater-or-equal integer
VF_floortoIround to the next smaller-or-equal integer
 
The target type may also be any of the other integer data types. A few examples should suffice: 
VF_choptoSIneglect the fractional part and store as short int
VF_ceiltoLIround up and store as long int
VF_floortoQIround downwards and store as quadruple integer, "quad"
VF_roundtoUround and store as unsigned
VF_ceiltoUSround up and store as unsigned short
VD_choptoULneglect the fractional part and store as unsigned long

Back to VectorLib Table of Contents   OptiVec home 

4.6.2 Comparisons

Functions performing comparisons are generally named VF_cmp... (where further letters and/or numbers specify the type of comparison desired). Every element of a vector can be compared either to 0, or to a constant C, or to the corresponding element of another vector. There are two possibilities: either the comparison is performed with the three possible answers "greater than", "equal to" or "less than". In this case, the results are stored as floating-point numbers (0.0, 1.0, or -1.0). Examples are:
 
VF_cmp0compare to 0
VD_cmpCcompare to a constant C
VE_cmpVcompare corresponding vector elements
 
The other possibility is to test if one of the following conditions is fulfilled: "greater than", "greater than or equal to", "equal to", "not equal to", "less than", or "less than or equal to". Here, the answers will be "TRUE" or "FALSE" (1.0 or 0.0). Examples are
 
VF_cmp_eq0check if equal to 0
VD_cmp_gtCcheck if greter than a constant C
VE_cmp_leVcheck if less than or equal to corresponding vector element
 
Alternatively, the indices of the elements for which the answer was "TRUE" may be stored in an index-array, as in:
 
VF_cmp_neCindstore indices of elements not equal to a constant C
VD_cmp_lt0indstore indices of elements less than 0
VE_cmp_geVindstore indices of elements greater than or equal to corresponding vector elements
 
While the basic comparison functions check against one boundary, there is a number of functions checking if a vector elements falls into a certain range:
 
VF_cmp_inclrange0C check if 0 <= x <= C  (C positive)
or  0 >= x >= C  (C negative)
VF_cmp_exclrange0C check if 0 < x < C  (C positive)
or  0 > x > C  (C negative)
VF_cmp_inclrangeCC check if CLo <= x <= CHi
VF_cmp_exclrangeCC check if CLo < x < CHi
VF_cmp_inclrange0Cind store indices of elements 0 <= x <= C  (C positive)
or  0 >= x > C  (C negative)
VF_cmp_exclrange0Cind store indices of elements 0 < x < C  (C positive)
or  0 > x > C  (C negative)
VF_cmp_inclrangeCCind store indices of elements CLo <= x <= CHi
VF_cmp_exclrangeCCind store indices of elements CLo < x < CHi
 
The following functions test if one or more values can be found in a vector: 
VF_iselementC returns TRUE, if C is an element of a vector
VF_iselementV checks for each element of a vector if it is contained in a table

Back to VectorLib Table of Contents   OptiVec home 

4.6.3 Direct Bit-Manipulation

For the integer data types, a number of bit-wise operations is available, which can be used, e.g., for fast multiplication and divisions by integer powers of 2. 
VI_shlshift the bits to the left
VI_shrshift the bits to the right
VI_orapply a bit mask in an OR operation
VI_xorapply a bit mask in an XOR operation
VI_notinvert all bits

Back to Table of Contents

4.6.4 Basic Arithmetics, Accumulations

As before, only the VF_ function is explicitly named, but the VD_ and VE_ functions exist as well; if it makes sense, the same is true for the complex and for the integer-type versions: 
VF_negYi = - Xi
VF_absYi = | Xi |
VCF_conjYi.Re = Xi.Re; Yi.Im = -(Xi.Re)
VF_invYi = 1.0 / Xi
 
VF_equCXi = C
VF_addCYi = Xi + C
VF_subCYi = Xi - C
VF_subrCYi = C - Xi
VF_mulCYi = Xi * C
VF_divCYi = Xi / C
VF_divrCYi = C / Xi
VF_modCYi = Xi mod C
VF_equVYi = Xi
VF_addVZi = Xi + Yi
VF_subVZi = Xi - Yi
VF_subrVZi = Yi - Xi
VF_mulVZi = Xi * Yi
VF_divVZi = Xi / Yi
VF_divrVZi = Yi / Xi
VF_modVZi = Xi mod Yi
VF_add2VZi = Xi + Y1i + Y2i
VF_sub2VZi = Xi - Y1i - Y2i
 
Besides these basic operations, several frequently-used combinations of addition and division have been included, not to forget the Pythagoras formula: 
VF_hypCYi = Xi / (Xi + C)
VF_redCYi = (Xi * C) / (Xi + C)
VF_visCYi = (Xi - C) / (Xi + C)
VF_hypotCYi = sqrt( Xi² + C² )
VF_hypVZi = Xi / (Xi + Yi)
VF_redVZi = (Xi * Yi) / (Xi + Yi)
VF_visVZi = (Xi - Yi) / (Xi + Yi)
VF_hypotVZi = sqrt( Xi² + Yi²)
 
All functions in the right column of the above two sections also exist in an expanded form (with the prefix VFx_...) in which the function is not evaluated for Xi itself, but for the expression
(a * Xi + b), e.g. 
VFx_addV Zi = (a * Xi + b) + Yi
VFx_divrV Zi = Yi / (a * Xi + b)
 
The simple algebraic functions exist also in yet another special form, with the result being scaled by some arbitrary factor. This scaled form gets the prefix VFs_
VFs_addV Zi = C * (Xi + Yi)
VFs_subV Zi = C * (Xi - Yi)
VFs_mulV Zi = C * (Xi * Yi)
VFs_divV Zi = C * (Xi / Yi)
 
Other simple operations include: 
VF_maxCset Yi equal to Xi or C, whichever is greater
VF_minCchoose the smaller of Xi and C
VF_maxVset Zi equal to Xi or Yi, whichever is greater
VF_minVset Zi equal to Xi or Yi, whichever is smaller
VF_limitlimit the range of values
VF_flush0set all values to zero which are below a preset threshold
VF_flushInvset all values to zero which are below a preset threshold and take the inverse of all other values
VF_intfracsplit into integer and fractional parts
VF_mantexpsplit into mantissa and exponent
 
While, in general, all OptiVec functions are for input and output vectors of the same type, the arithmetic functions exist also for mixed-type operations between the floating-point and the integer types. The result is always stored in the floating-point type. Examples are:
 
VF_addVIfVector Z = fVector X + iVector Y
VD_mulVULdVector Z = dVector X * ulVector Y
VE_divrVBIeVector Z = biVector Y / eVector X

Similarly, there exists a family of functions for the accumulation of data in either the same type or in higher-precision data types. Some examples are: 

VF_accVfVector Y += fVector X
VD_accVFdVector Y += fVector X
VF_accVIfVector Y += iVector X
VQI_accVLIqiVector Y += liVector X
 
Additionally, within the floating-point data-types, you can accumulate two vectors at once:  
VF_acc2VfVector Y += fVector X1 + fVector X2
VD_acc2VFdVector Y += fVector X1 + fVector X2

Again only within the floating-point data-types, you can also accumulate squares and products:

VF_accV2fVector Y += fVector X2
VD_accVF2dVector Y += fVector X2
VCF_accVmulVconjcfVector Y += cfVector X * cfVector Y*

Back to VectorLib Table of Contents   OptiVec home 

4.6.5 Geometrical Vector Arithmetics

In its geometrical interpretation, a vector is a pointer, with its elements representing the coordinates of a point in n-dimensional space. There are a few functions for geometrical vector arithmetics, namely 
VF_scalprod scalar product of two vectors
VF_xprod cross-product (or vector product) of two vectors
VF_Euclid Euclidean norm

If, on the other hand, two real input vectors X and Y, or one complex input vector XY, define the coordinates of several points in a planar coordinate system, there is a function to rotate these coordinates:

VF_rotateCoordinates counter-clockwise rotation of the input coordinates specified by the vectors X and Y; the result is returned in the vectors Xrot and Yrot.
VCF_rotateCoordinates counter-clockwise rotation of the input coordinates specified by the cartesian complex vector XY; the result is returned in the vector XYrot.

Back to VectorLib Table of Contents   OptiVec home 

4.6.6 Powers

The following functions raise arbitrary numbers to specified powers. The extra-fast "unprotected versions" can be employed in situations where you are absolutely sure that all input elements yield valid results. Due to the much more efficient vectorization permitted by the absence of error checks, the unprotected functions are up to 1.8 times as fast as the protected versions. (This is true from the Pentium CPU on; on older computers, almost nothing is gained.) Be, however, aware of the price you have to pay for this increase in speed: in case of an overflow error, the program will crash without any warning.
 
normal versionunprotected versionoperation
VF_squareVFu_squaresquare
VF_cubicVFu_cubiccubic
VF_quarticVFu_quarticquartic (fourth power)
VF_ipowVFu_ipowarbitrary integer powers
VF_pown.a.fractional powers
VF_powexpn.a.fractional powers, multiplied by exponential function: xrexp(x)
VF_polyVFu_polypolynomial
 
The following group of functions is used to raise specified numbers to arbitrary powers: 
VF_pow10 fractional powers of 10
VF_ipow10 integer powers of 10 (stored as floating-point numbers)
VF_pow2 fractional powers of 2
VF_ipow2 integer powers of 2 (stored as floating-point numbers)
VF_exp exponential function
VF_exp10 exponential function to the basis 10 (identical to VF_pow10)
VF_exp2 exponential function to the basis 2 (identical to VF_pow2)
VF_expArbBase exponential function of an arbitrary base
VF_sqrt square-root (which corresponds to a power of 0.5)
 
All of these functions exist also in the expanded "VFx_" form, like
VFx_square: Yi = (a * Xi + b)² 
The expanded form of the unprotected functions has the prefix VFux_.

The complex-number equivalents are available as well, both for cartesian and polar coordinates. Additionally, two special cases are covered:
 

VCF_powReExpo real, fractional powers of complex numbers
VCF_exptoP takes a cartesian input vector, returning its exponential function in polar coordinates.

Back to VectorLib Table of Contents   OptiVec home 

4.6.7 Exponentials and Hyperbolic Functions

A variety of functions are derived from the exponential function VF_exp (which itself has already been mentioned in the last section).
 
VF_exp exponential function
VF_expc complementary exponential function Yi = 1 - exp[Xi]
VF_expmx2 exponential function of the negative square of the argument,
Yi = exp( -Xi² ). This is a bell-shaped function.
VF_powexpfractional powers, multiplied by exponential function, Xirexp(Xi)
VF_Gauss Gaussian distribution function
VF_erf Error function (Integral over the Gaussian distribution)
VF_erfc complementary error function, 1 - erf( Xi )
 
The vectorized hyperbolic functions are available as: 
VF_sinh hyperbolic sine
VF_cosh hyperbolic cosine
VF_tanh hyperbolic tangent
VF_coth hyperbolic cotangent
VF_sech hyperbolic secant
VF_cosech hyperbolic cosecant
VF_sech2 square of the hyperbolic secant

Back to VectorLib Table of Contents   OptiVec home 

4.6.8 Logarithms

VF_log10 decadic logarithm (to the basis 10)
VF_log natural logarithm (to the basis e)
VF_ln synonym for VF_log
VF_log2 binary logarithm (to the basis 2)
 
Again, the cartesian-complex equivalents exist as well. The polar-complex versions, however, are special in that their output is always in cartesian coordinates:
VPF_log10toC decadic logarithm (to the basis 10)
VPF_logtoC natural logarithm (to the basis e)
VPF_lntoC synonym for VPF_logtoC
VPF_log2toC binary logarithm (to the basis 2)

As a special form of the decadic logarithm, the Optical Density is made available by a family of functions of which some examples are contained in the following table: 
VF_ODOD = log10( X0/X ) for fVector as input and as output
VF_ODwDarkOD = log10( (X0-X0Dark) / (X-XDark) ) for fVector as input and as output
VUS_ODtoFOD, calculated in float precision for usVector input
VUL_ODtoDOD, calculated in double precision for ulVector input
VQI_ODtoEwDarkOD with dark-current correction, calculated in extended precision for qiVector input

Back to VectorLib Table of Contents   OptiVec home 

4.6.9 Trigonometric Functions

The basic trigonometric functions are available in two variants. The first variant follows the usual rules of error handling for math functions, whereas the second is for situations where you know beforehand that all input arguments will be in the range -2p <= Xi <= +2p. If you choose to employ these extra-fast reduced-range functions, you really have to be absolutely sure about your input vectors, as these functions will crash without warning in the case of any input number outside the range specified above. The reduced-range functions are available only for the sine and cosine, as all other trigonometric functions need error checking and handling anyway, even in this range.
 
VF_sinsine
VFr_sinextra-fast "reduced-range" sine function for -2p <= Xi <= +2p
VF_coscosine
VFr_coscosine for -2p <= Xi <= +2p
VF_sincossine and cosine at once
VFr_sincossine and cosine for -2p <= Xi <= +2p
VF_tantangent
VF_cotcotangent
VF_secsecant
VF_coseccosecant
 
The following functions yield the squares of the trigonometric functions in a more efficient way than by first calculating the basic functions and squaring afterwards: 
VF_sin2sine²
VFr_sin2sine² for -2p <= Xi <= +2p
VF_cos2cosine²
VFr_cos2cosine² for -2p <= Xi <= +2p
VF_sincos2sine² and cosine² at once
VFr_sincos2sine² and cosine² for -2p <= Xi <= +2p
VF_tan2tangent²
VF_cot2cotangent²
VF_sec2secant²
VF_cosec2cosecant²
 
A very efficient way to calculate the trigonometric functions for arguments representable as rational multiples of p (PI) is supplied by the trigonometric functions with the suffix "rpi" (meaning "rational multiple of p"). Here, r = p / q, where q is constant and p is given by the input vector elements: 
VF_sinrpisine of p/q * p
VF_cosrpicosine of p/q * p
VF_sincosrpisine and cosine of p/q * p at once
VF_tanrpitangent of p/q * p
VF_cotrpicotangent of p/q * p
VF_secrpisecant of p/q * p
VF_cosecrpicosecant of p/q * p
 
Even more efficient versions use tables to obtain frequently-used values; these versions are denoted by the suffixes "rpi2" (multiples of p divided by an integer power of 2) and "rpi3" (multiples of p over an integer multiple of 3). Examples are: 
VF_sinrpi2 sine of p / 2n * p
VF_tanrpi3 tangent of p / (3*n) * p
 
Two more special trigonometric functions are: 
VF_sinc sinc function, Yi = sin( Xi ) / Xi
VF_Kepler Kepler function, calculating the time-dependent angular position of a planet or comet
 
Vectorized inverse trigonometric functions are available as 
VF_asinarc sin
VF_acosarc cos
VF_atanarc tan
VF_atan2 arc tan of ratios, Zi = atan( Yi / Xi )

Back to VectorLib Table of Contents   OptiVec home 

4.7 Analysis

There is a number of functions probing the analytical properties of data arrays: 
VF_derivV derivative of a Y-array with respect to an X-array
VF_derivC the same for constant intervals between the X-values
VF_integralV value of the integral of a Y-array over an X-array
VF_runintegralV point-by-point ("running") integral
VF_integralC integral over an equally spaced X-axis
VF_runintegralC point-by-point integral over an equally spaced X-axis
VF_ismonoton test if an array is monotonously rising or falling
VF_iselementC test, if a given value occurs within a vector
VF_searchC search an ordered table for the entry whose value comes closest to a preset value C
VF_localmaxima detect local maxima (points whose right and left neighbours are smaller)
VF_localminima detect local minima (points whose right and left neighbours are larger)
VF_max detect global maximum
VF_min detect global minimum
VF_maxind global maximum and its index
VF_minind global minimum and its index
VF_absmax global maximum absolute value
VF_absmin global minimum absolute value
VF_absmaxind global maximum absolute value and its index
VF_absminind global minimum absolute value and its index
VF_maxexp global maximum exponent
VF_minexp global minimum exponent
VF_runmax "running" maximum
VF_runmin "running" minimum
 
The complex equivalents of the last group of functions are: 
VCF_maxReIm maximum real and imaginary parts separately
VCF_minReIm minimum real and imaginary parts separately
VCF_absmaxReIm maximum absolute real and imaginary values separately
VCF_absminReIm minimum absolute real and imaginary values separately
VCF_absmax largest magnitude (absolute value)
VCF_absmin smallest magnitude
VCF_cabsmax complex number of largest magnitude
VCF_cabsmin complex number of smallest magnitude
VCF_sabsmax complex number for which the sum |Re| + |Im| is largest
VCF_sabsmin smallest complex number in terms of the sum |Re| + |Im|
VCF_absmaxind largest magnitude (absolute value) and its index
VCF_absminind smallest magnitude and its index
 
Sums, products, etc. are available by functions grouped as statistical building blocks and summarized in chapter 4.9

To determine the center of gravity of a vector, you have the choice between the following two functions:
 

VF_centerOfGravityIndcenter of gravity, returned as an interpolated element index
VF_centerOfGravityVcenter of gravity of a Y vector with explicitly given X axis

Back to VectorLib Table of Contents   OptiVec home 

4.8 Signal Processing:
Fourier Transforms and Related Topics

The following list of functions is available for signal processing applications:
VF_FFTtoC forward Fast Fourier Transform (FFT) of a real vector; the result is a cartesian complex vector
VF_FFT forward and backward FFT of a real vector; the result of the forward FFT is packed into a real vector of the same size as the input vector
VCF_FFT forward and backward FFT of a complex vector
MF_Rows_FFTFFT along the rows of a matrix; this function may be used for batch-processing of several vectors of identical size, stored as the rows of a matrix
MF_Cols_FFTFFT along the columns of a matrix; this function may be used for batch-processing of several vectors of identical size, stored as the columns of a matrix
VF_convolve / VF_convolvewEdit convolution with a given response function
VF_deconvolve / VF_deconvolvewEdit deconvolution, assuming a given response function
VF_filter spectral filtering
VF_spectrum spectral analysis
VF_xspectrum cross-spectral density of two signals (complex one-sided variant)
VF_xspectrumAbs cross-spectral density of two signals (absolute values)
VF_coherence coherence function between two signals
VF_autocorr autocorrelation function of a signal
VF_xcorr cross-correlation function of two signals
VF_setRspEdit set default editing threshold for the filter in convolutions and deconvolutions (decides over the treatment of "lost" frequencies)
VF_getRspEdit retrieve the current default editing threshold

Although they do not use Fourier transform methods, the functions VF_biquad (bi-quadratic audio filtering) and VF_smooth (crude form of frequency filtering which removes high-frequency noise) should be mentioned here.

Back to VectorLib Table of Contents   OptiVec home 

4.9 Statistical Functions and Building Blocks

The following collection of statistical functions is offered by OptiVec:
 
VF_sum sum of all elements
VI_fsum sum of all elements of an integer vector, accumulated as a floating point number in double or extended precision
VF_prod product of all elements
VF_ssq sum-of-squares of all elements
VF_sumabs sum of absolute values of all elements
VF_rms root-of-the-mean-square of all elements
VF_runsum running sum
VF_runprod running product
VF_sumdevC sum over the deviations from a preset constant, sum( |Xi-C| )
VF_sumdevV sum over the deviations from another vector, sum( |Xi-Yi| )
VF_sumdevVwSaturation sum over the deviations from another vector, sum( |Xi-Yi| ) with saturation of possible overflow to HUGE_VAL
VF_subV_sumabs difference between two vectors and sum over the absolute values of the results
VF_avdevC average deviation from a preset constant, 1/N * sum( |Xi-C| )
VF_avdevV average deviation from another vector, 1 / N * sum( |Xi-Yi| )
VF_ssqdevC sum-of-squares of the deviations from a preset constant,
sum( (Xi - C)² )
VF_ssqdevV sum-of-squares of the deviations from another vector,
sum( (Xi - Yi)² )
VF_ssqdevVwSaturation sum-of-squares of the deviations from another vector with saturation of possible overflow to HUGE_VAL
VF_subV_ssq difference between two vectors and sum-of-squares over the results
VF_chi2 chi-square merit function
VF_chi2wSaturation chi-square merit function with saturation of possible overflow to HUGE_VAL
VF_subV_chi2 difference between two vectors and chi-square merit function
VF_chiabs "robust" merit function, similar to VF_chi2, but based on absolute instead of squared deviations
VF_chiabswSaturation The same as VF_chiabs, but with saturation of possible overflow to HUGE_VAL
VF_subV_chiabs difference between two vectors and chiabs merit function
VF_mean equally-weighted mean (or average) of all elements
VF_meanwW "mean with weights" of all elements
VF_meanabs equally-weighted mean (or average) of the absolute values of all elements
VF_selected_mean averages only those vector elements which fall into a specified range, thus allowing to exclude outlier points from the calculation of the mean
VF_varianceC variance of a distribution with respect to a preset constant value
VF_varianceCwW the same with non-equal weighting
VF_varianceV variance of one distribution with respect to another
VF_varianceVwW the same with non-equal weighting
VF_meanvar mean and variance of a distribution simultaneously
VF_meanvarwW the same with non-equal weighting
VF_median median of a distribution
VF_corrcoeff linear correlation coefficient of two distributions
VF_distribution bins data into a discrete one-dimensional distribution function
VF_min_max_mean_stddev simultaneous calculation of the minimum, maximum, mean, and standard deviation of a one-dimensional distribution

Back to VectorLib Table of Contents   OptiVec home 

4.10 Data Fitting

Ranging from a simple linear regression to complex fitting problems involving multiple data sets and nonlinear functions with many adjustable parameters, OptiVec offers routines for virtually all practically occurring tasks of data fitting. As all of them, except for simple linear regression, rely on matrix methods, they actually form a part of MatrixLib. This means you have to #include <MFstd.h> (<MDstd.h>< MEstd.h>) or the unit MFstd, (MDstd, MEstd).

A detailed description of the various data-fitting concepts is given elsewhere. Therefore, at this place, the available X-Y fitting functions are only summarized in the following table:
 

VF_linregress equally-weighted linear regression on X-Y data
VF_linregresswW the same with non-equal weighting
VF_polyfit fitting of one X-Y data set to a polynomial
VF_polyfitwW the same for non-equal data-point weighting
VF_linfit fitting of one X-Y data set to an arbitrary function linear in its parameters
VF_linfitwW the same for non-equal data-point weighting
VF_setLinfitNeglect set threshold to neglect (i.e. set equal to zero) a fitting parameter A[i], if its significance is smaller than the threshold
VF_getLinfitNeglect retrieve current significance threshold
VF_nonlinfit fitting of one X-Y data set to an arbitrary, possibly non-linear function
VF_nonlinfitwW the same for non-equal data-point weighting
VF_multiLinfit fitting of multiple X-Y data sets to one common linear function
VF_multiLinfitwW the same for non-equal data-point weighting
VF_multiNonlinfit fitting of multiple X-Y data sets to one common nonlinear function
VF_multiNonlinfitwW the same for non-equal data-point weighting
 

Back to VectorLib Table of Contents   OptiVec home 

4.11 Input and Output

VF_cprint print the elements of a vector to the screen (or "console" - hence the "c" in the name) into the current text window, automatically detecting its height and width. After printing one page, the user is prompted to continue. (Only for console applications)
VF_print is similar to VF_cprint in that the output is directed to the screen, but there is no automatic detection of the screen data. The symbolic constant V_consoleWindowWidth (defined in <VecLib.h> or in the unit VecLib with a default value of 150) determines the linewidth, and no division into pages is made. (Only for console applications)
VF_fprint print a vector to a stream.
VF_chexprint Similar to VF_cprint, but printed in hexadecimal format.
VF_hexprint Similar to VF_print, but printed in hexadecimal format.
VF_fhexprint Similar to VF_fprint, but printed in hexadecimal format.
VF_write write data in ASCII format in a stream
VF_read read a vector from an ASCII file
VF_nwrite write n vectors of the same data type as the columns of a table into a stream
VF_nread read the columns of a table into n vectors of the same type
VF_store store data in binary format
VF_recall retrieve data in binary format
 
The following functions allow to modify the standard settings of VF_write, VF_nwrite and VI_read
VF_setWriteFormat define a certain number format
VF_setWriteSeparate define a separation string between successive elements, written by VF_write
VF_setNWriteSeparate define a separation string between the columns written by VF_nwrite
V_setRadix define a radix different from the standard of 10 for the whole-number variants of the V..read functions

Back to VectorLib Table of Contents   OptiVec home 

4.12 Graphics

VectorLib includes a range of data-plotting routines. Before any of them may be used, VectorLib graphics has to be initialized:
 
V_initPlot initialize VectorLib graphics functions. No shut-down is needed at the end, since the Windows graphics functions always remain accessible. V_initPlot automatically reserves a part of the screen for plotting operations. This part comprises about 2/3 of the screen on the right side. Above, one line is left for a heading. Below, a few lines are left empty. To change this default plotting region, call V_setPlotRegion after V_initPlot.
V_initPrint initialize VectorLib graphics functions and direct them to a printer. By default, one whole page is reserved for plotting. In order to change this, call V_setPlotRegion after V_initPrint.
V_setPlotRegion set a plotting region different from the default
 
VectorLib distinguishes between two sorts of plotting functions, AutoPlot and DataPlot. All AutoPlot functions (e.g., VF_xyAutoPlot) execute the following steps:
  1. define a viewport within the plotting region (which is either the default region or the one defined by calling V_setPlotRegion)
  2. clear the viewport
  3. generate a Cartesian coordinate system with suitably scaled and labeled axes
  4. plot the data according to the parameters passed to the function
All DataPlot functions execute only the last step. They assume that a coordinate system already exists from a previous call to any of the AutoPlot functions, to V_findAxes, or to V_drawAxes. The new plot is added to the existing one.
For all plotting functions, the different plot styles (symbols, lines, and colors), are specified as parameters, see VF_xyAutoPlot. Here is a list of the available AutoPlot and DataPlot routines:
 
VF_xyAutoPlot display an automatically-scaled plot of an X-Y vector pair
VF_yAutoPlot plot a single Y-vector, using the index as X-axis
VF_xy2AutoPlot plot two X-Y pairs at once, scaling the axes in such a way that both vectors fit into the same coordinate system
VF_y2AutoPlot the same for two Y-vectors, plotted against their indices
VF_xyDataPlot plot one additional set of X-Y data
VF_yDataPlot plot one additional Y vector over its index
 
Cartesian complex arrays are printed into the complex plane (the imaginary parts versus the real parts), using
 
VCF_autoPlot plot one cartesian complex vector
VCF_2AutoPlot plot two cartesian complex vectors simultaneously
VCF_dataPlot plot one additional cartesian complex vector
 
It is possible to draw more than one coordinate systems into a given window on the screen. The position of each coordinate system must be specified by V_setPlotRegion. "Hopping" between the different coordinate systems and adding new DataPlots after defining new viewports (e.g., for text output) is made possible by the following functions:
 
V_continuePlot go back to the viewport of the last plot and restore its scalings
V_getCoordSystem get a copy of the scalings and position of the current coordinate system
V_setCoordSystem restore the scalings and position of a coordinate system; these must have been stored previously, using V_getCoordSystem
 

Continue with chapter 5. Error Handling
Back to VectorLib Table of Contents      OptiVec home 

Copyright © 1996-2022 OptiCode - Dr. Martin Sander Software Development

Last modified: 21 June 2022