Boost logo

Ublas :

From: Angus Leeming (angus.leeming_at_[hidden])
Date: 2005-08-04 10:45:37


Any suggestions on how to rewrite the code below without the loop? The
best I can come up with is:

    return ScalarVector(np, 2.0) -
           (2.0 * z_vec) -
           (18.0 * element_prod(z_vec, z_vec)) +
           (18.0 * element_prod(z_vec, element_prod(z_vec, z_vec)));

which isn't exactly easier to read ;-)

Angus

-----------------------------------------------------------------------
Existing code:

typedef boost::numeric::ublas::vector<double> Vector;

Vector const my_function(Vector const & z_vec)
{
        typedef Vector::size_type size_type;
        typedef boost::numeric::ublas::scalar_vector<double> ScalarVector;
        size_type const np = z_vec.size();
        Vector result(ScalarVector(np, 0.0));

        for (size_type i = 0; i < np; ++i) {
                double const z = z_vec[i];
                double const z2 = z * z;
                double const z3 = z * z2;
                result(i) = 2.0 - (2.0 * z) - (18.0 * z2) + (18.0 * z3);
        }

        return result;
}