The*_*ude 2 c numerical linear-algebra scientific-computing
我在使用CBLAS执行外部产品时遇到问题.我的代码如下:
//===SET UP===//
double x1[] = {1,2,3,4};
double x2[] = {1,2,3};
int dx1 = 4;
int dx2 = 3;
double X[dx1 * dx2];
for (int i = 0; i < (dx1*dx2); i++) {X[i] = 0.0;}
//===DO THE OUTER PRODUCT===//
cblas_dgemm(CblasRowMajor, CblasNoTrans, CblasTrans, dx1, dx2, 1, 1.0, x1, dx1, x2, 1, 0.0, X, dx1);
//===PRINT THE RESULTS===//
printf("\nMatrix X (%d x %d) = x1 (*) x2 is:\n", dx1, dx2);
for (i=0; i<4; i++) {
for (j=0; j<3; j++) {
printf ("%lf ", X[j+i*3]);
}
printf ("\n");
}
Run Code Online (Sandbox Code Playgroud)
我明白了:
Matrix X (4 x 3) = x1 (*) x2 is:
1.000000 2.000000 3.000000
0.000000 -1.000000 -2.000000
-3.000000 0.000000 7.000000
14.000000 21.000000 0.000000
Run Code Online (Sandbox Code Playgroud)
但正确的答案可以在这里找到:https: //www.sharcnet.ca/help/index.php/BLAS_and_CBLAS_Usage_and_Examples
我已经看到:C中kronecker产品的高效计算
但是,它并没有帮助我,因为他们实际上并没有说如何利用dgemm来实际做到这一点......
有帮助吗?我在这做错了什么?
你可以用dgemm做到这一点,但是使用dger会更加风格化,这是一个专门的外部产品实现.因此,它更容易正确使用:
cblas_dger(CblasRowMajor, /* you’re using row-major storage */
dx1, /* the matrix X has dx1 rows ... */
dx2, /* ... and dx2 columns. */
1.0, /* scale factor to apply to x1x2' */
x1,
1, /* stride between elements of x1. */
x2,
1, /* stride between elements of x2. */
X,
dx2); /* leading dimension of matrix X. */
Run Code Online (Sandbox Code Playgroud)
dgemm 确实具有传递\beta = 0初始化结果矩阵的优点,这使您无需在调用之前自己将其显式归零.@Artem Shinkarov的回答提供了如何使用dgemm的很好的描述.
小智 5
BLAS 中的接口不是很方便,但是,让我们尝试弄清楚。首先,假设我们所有的矩阵都在 RowMajor 中。现在我们有以下设置
row col
x1: dx1 1 (A)
x2: 1 dx2 (B)
X: dx1 dx2 (C)
Run Code Online (Sandbox Code Playgroud)
现在,我们只需要根据文档填写调用,文档中指定了
C = \alpha A*B + \beta C
Run Code Online (Sandbox Code Playgroud)
所以我们得到:
cblas_dgemm (CblasRowMajor, CblasNoTrans, CblasNoTrans,
(int)dx1, /* rows in A */
(int)dx2, /* columns in B */
(int)1, /* columns in A */
1.0, x1, /* \alpha, A itself */
(int)1, /* Colums in A */
x2, /* B itself */
(int)dx2, /* Columns in B */
0.0, X, /* \beta, C itself */
(int)dx2 /* Columns in C */);
Run Code Online (Sandbox Code Playgroud)
所以这应该可以完成我希望的工作。下面是dgemm的参数说明:链接