// File: vector_expr.cpp #include <iostream> #include <boost/numeric/mtl/mtl.hpp> int main(int argc, char* argv[]) { using namespace mtl; typedef std::complex<double> cdouble; dense_vector<cdouble> u(10), v(10); dense_vector<double> w(10), x(10, 4.0); for (int i= 0; i < size(v); i++) v[i]= cdouble(i+1, 10-i), w[i]= 2 * i + 2; u= v + w + x; std::cout << "u is " << u << "\n"; u-= 3 * w; std::cout << "u is " << u << "\n"; u+= dot(v, w) * w + 4.0 * v + 2 * w; std::cout << "u is " << u << "\n"; std::cout << "i * w is " << cdouble(0,1) * w << "\n"; return 0; }
The mathematical definition of vector spaces requires that vectors can be added, multiplied with scalar values and the results can be assigned to vectors. In MTL4, the vectors must have the same algebraic shape, see ashape, for addition and assignment, i.e. column vectors cannot be assigned to row vectors. If the elements of the vectors are vectors themselves or matrices then the elements must also be of the same algebraic shape.
Products of scalars and vectors are implemented by a view, see vector::scaled_view, and vector elements are multiplied with the factor when accessing an element of the view. Please notice that the scaling factor's type is not required to be identical with the vector's value type. Furthermore, the value type of the view can be different from the vector's value type if necessary to represent the products. The command is an example for it: multiplying a double vector with a complex number requires a complex vector view to guarantee the correctness of the results.
Traditional definitions of operators perform computations in temporary variables that are returned at the end of the calculation. The presence of multiple operators, say n, in a single expression (which is always the case except for an assignment without numerics) requires then the execution of n loops (possibly more to copy the temporaries on the stack). If the vectors are too large for the cache, values must be loaded repeatedly from slower memories. Expression templates circumvent this repeated loading of vector elements by performing only one loop.
Return to Matrix Assignment Table of Content Proceed to Rich Vector Expressions
Vector Expressions -- MTL 4 -- Peter Gottschling and Andrew Lumsdaine
-- Generated on 19 May 2009 by Doxygen 1.5.5 -- Copyright 2007 by the Trustees of Indiana University.