[英]Incorrect result for matrix-vector product using cblas_dgemv()
我正在嘗試使用cblas.h中聲明的例程'cblas_dgemv()'計算矩陣向量乘積。 代碼如下:
#include <cblas.h>
#include <iostream>
using namespace std;
/* compile with: g++ test.cpp -o test -lblas */
int main (int argc, char** argv)
{
/* We store the following 3x4 array in column major form:
A = [1.83292 0.267964 0.382422 0.520162
0.428562 0.720323 0.839606 1.30816
0.388731 0.619452 1.01375 0.229333 ];
*/
const double A[12] = { 1.83292,
0.428562,
0.388731,
0.267964,
0.720323,
0.619452,
0.382422,
0.839606,
1.01375,
0.520162,
1.30816,
0.229333};
/* The vector X is:
X = [ 0.570695, 0.670179, 0.927146, 0.297343 ]';
where ' is transpose.
*/
const double X[4] = { 0.570695, 0.670179, 0.927146, 0.297343};
double Y[4] = {0, 0, 0, 0};
/* Calculate Y = A*X (alpha = 1 and beta = 0)
*/
cblas_dgemv(CblasColMajor, CblasNoTrans, 3, 4, 1, A, 3, X, 1, 0, Y, 1);
/* If I was correct, I should have got:
Y =[1.69366 1.20999 1.72082 1.38618] = A*X;
but I get:
Y = [1.73485 1.89473 1.64507 0] = A'*X;
*/
cout<<"Y = [";
for ( unsigned int i = 0; i < 4; i++ )
cout<<Y[i]<<" ";
cout<<"]";
}
但是,我一直得到Y = A'* X,而不是得到Y = A * X,其中'表示轉置。 我不確定我是否在某個地方犯了一些經典的愚蠢錯誤,但是經過數小時的嘗試,我仍然無法找出問題所在。 請幫忙!!
如果需要,我正在使用Linux版本3.2.0-4-amd64(Debian 4.6.3-14))#1 SMP Debian 3.2.57-3 + deb7u2和g ++(Debian 4.4.7-2)4.4.7 。 提前致謝。
你的數學錯了。 3 x 4矩陣和4分量向量的乘積是3分量向量。 在您的情況下,A * X的乘積為[1.73485 1.89473 1.64507]。
如果將A的轉置相乘(4x3),則需要3分量向量與之相乘,乘積是4分量向量。 我們將X'稱為X'的前三個成分-> X'= [0.570695、0.670179、0.927146]。 然后A'* X'= [1.693662 1.209994 1.720827 1.386180]。
#include <stdio.h>
void dgemv(const double *A, const double *u, double *v, const int n, const int m) {
for(int i=0; i<n; i++) {
double sum = 0;
for(int j=0; j<m; j++) {
sum += A[m*i+j]*u[j];
}
v[i] = sum;
}
}
int main() {
const double A[12] = {1.83292 , 0.267964, 0.382422, 0.520162,
0.428562, 0.720323, 0.839606, 1.30816 ,
0.388731, 0.619452, 1.01375 , 0.229333};
const double AT[12] = {1.83292 , 0.428562, 0.388731,
0.267964, 0.720323, 0.619452,
0.382422, 0.839606, 1.01375 ,
0.520162, 1.30816 , 0.229333};
const double X[4] = { 0.570695, 0.670179, 0.927146, 0.297343};
const double X2[4] = { 0.570695, 0.670179, 0.927146};
double Y[3], Y2[4];
dgemv(A, X, Y, 3,4);
for(int i=0; i<3; i++) printf("%f ", Y[i]); printf("\n");
dgemv(AT, X2, Y2, 4,3);
for(int i=0; i<4; i++) printf("%f ", Y2[i]); printf("\n");
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.