7

我在仿真软件中工作,对数组进行的众多操作之一就是将向量缩放一个数字。

我有这样的代码:

//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;
}

我有可用的 MKL 库,因此如果我的计算是“就地”完成的,则可以编写以下内容:

cblas_dscal(n, alpha, &input[0], 1);

但是,这会改变input变量,这不是我想要的。

我尝试使用,mkl_domatcopy()但此操作非常慢。

4

3 回答 3

1

我想出的解决方案是调用cblas_dcopy()then cblas_dscal()

它不是世界上最好的,但它仍然比原始循环快。

于 2014-01-14T11:44:37.890 回答
1

来自 MKL 参考:

cblas_?axpy 例程执行向量-向量运算,定义为

y := a * x + y 其中:a是标量,xy是向量,每个向量的元素数量等于n

于 2017-02-05T07:32:47.613 回答
1

在类似 BLAS 的扩展中有一个名为cblas_?axpby的例程

这是文档的摘录:

缩放两个向量,将它们相加并将结果存储在向量中。

不同之cblas_?axpy处在于您在结果向量 y 上有第二个缩放参数。在您的情况下,您可以只设置b := 0.0并因此在一个呼叫中进行不合适的缩放,而不是两个cblas_dcopy()and cblas_dscal()

您的代码可能如下所示:

//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:
cblas_daxpby (output.size(), alpha, input.data(), 1, 0.0, output.data(), 1);
于 2017-11-10T08:57:45.950 回答