Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MKL or BLAS routine to multiply vector by a scalar out-of-place

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.

like image 563
Edison Gustavo Muenz Avatar asked Jan 13 '14 20:01

Edison Gustavo Muenz


People also ask

How do you multiply a vector by a scalar?

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 .

What are the two ways of multiplying vectors?

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").

What is scalar multiplication and vector multiplication?

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).


1 Answers

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.

like image 189
Edison Gustavo Muenz Avatar answered Sep 17 '22 01:09

Edison Gustavo Muenz