I work in simulation software and one of the many operations done on arrays is scaling a vector by a number.
I have code like this:
//Just some initialization code, don't bother about this part
int n = 10000;
std::vector<double> input(n, 42.0);
std::vector<double> output(input.size());
double alpha = 69.0;
//the actual calculation:
for (size_t i = 0; i < n; ++i) {
output[i] = input[i] * alpha;
}
I have the MKL library available, so if my calculations are done "in-place" the following can be written:
cblas_dscal(n, alpha, &input[0], 1);
However, this will change the input
variable, which is not what I want.
I tried using the mkl_domatcopy()
but it is very slow for this operation.
To multiply a vector by a scalar, multiply each component by the scalar. If →u=⟨u1,u2⟩ has a magnitude |→u| and direction d , then n→u=n⟨u1,u2⟩=⟨nu1,nu2⟩ where n is a positive real number, the magnitude is |n→u| , and its direction is d .
Two types of multiplication involving two vectors are defined: the so-called scalar product (or "dot product") and the so-called vector product (or "cross product").
Scalar multiplication is the multiplication of a vector by a scalar (where the product is a vector), and is to be distinguished from inner product of two vectors (where the product is a scalar).
The solution I came up with was calling cblas_dcopy()
then cblas_dscal()
.
It is not the best of all worlds but it is still faster than the raw loop.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With