3 个矩阵相乘求和 [英] multiplication of 3 matrices in a sum
问题描述
我想计算:
result = SUM (c=0,N) { V_ck * U_lc * S_c }
但是我的 2D 矩阵被索引为 1D 并存储为列主.
But my 2D matrices are indexed as 1D and stored as column major.
我正在尝试:
float *A,*B;
int M,N;
A = (float *) malloc( M * N * sizeof(float) );
B = (float *) malloc( M * sizeof(float) );
float *S = (float *)malloc( N * sizeof( float) );
float *U = (float *)malloc( M * M * sizeof( float) );
float *V = (float *)malloc( N * N * sizeof( float) );
float * result = (float *) malloc( M * N * sizeof(float) );
float thesum=0;
for (int k=0; k < M ; k++) {
for (int l=0 ; l < N; l++) {
for ( int c=0; c < N; c++) {
thesum += V[ k+c*N ] * S[c] * U[l*M + k];
result[ k+l*M ]=thesum;
}
}
}
我有一个大错误,我认为在上面,因为我需要另一个循环?为了首先正确地进行乘法,然后使用:
I have one big mistake ,I think in the above,because I need another loop ? in order to do properly the multiplication first and then use the:
for ( int c=0; c
求和的循环,对吧?
然后,我是否必须创建一个数组来保存乘法值,然后使用这个数组来保存求和值?
And then, do I have to create an array which will hold the multiplication values and then use this array to hold the summation values?
如果我使用 2D 表示法,我会简单地使用 U[l][k]
等等.
If I were using 2D notation , I would simple use U[l][k]
and so on.
但现在,我对如何应用适当的索引感到困惑.
But now,I am confused about how to apply the appropriate indices.
我希望有人解释我应该如何处理这个问题.
And I want someone to explain me how should I proceed with this.
推荐答案
如果我使用 2D 表示法,我会简单地使用 U[l][k] 等等.
If I were using 2D notation , I would simple use U[l][k] and so on.
因此,添加该抽象层 - 不要让其他一切变得复杂.你有:
So, add that layer of abstraction - don't let everything else get complicated. You have:
A = (float *) malloc( M * N * sizeof(float) );
至少,您可以使用:
float& at(float* p, int rows, int col, int row) { return p[rows * col + row]; }
(根据口味重新排列参数)
(reorder arguments to taste)
然后你可以说:
at(A, M, col, row)
(或类似的 - 我不会发誓我把所有的行/列名称都弄对了 - 但恕我直言,你应该使用 Rows 和 Columns 而不是 M 和 N,所以我不会为此大吃一惊.)
(Or similar - I wouldn't swear I got all the rows/column names right - but IMHO you should have used Rows and Columns instead of M and N so I'm not going to bust a gut over it.)
如果你想更高级一点,在 C++ 中,你可以将分配包装在一个存储指针和 #rows/columns 的类中,然后重载 float&operator()(int col, int row)
和 const float&operator()(int col, int row) const
(或者只是 float operator()(int col, int row) const
如果您不关心获取地址的能力数组条目).
If you want to get a little fancier, in C++ you can wrap the allocations in a class that stores the pointer and #rows/columns, then overloads float& operator()(int col, int row)
and const float& operator()(int col, int row) const
(or just float operator()(int col, int row) const
if you don't care about ability to take the address of the array entry).
这篇关于3 个矩阵相乘求和的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!