c - 矩阵与 vector 相乘

标签 c vector matrix multiplication

我需要将矩阵和 vector 相乘。

为了实现这一点,我编写了一个带参数的函数:

float** M 尺寸的最大值:m x n。

float* V 长度为 n 的 vector 。

float* R 我在其中存储结果,长度为 m 的 vector ,已分配。

int m, int n 长度。

这是我的代码:

int i,j;

for (i=0;i<m;i++){
    for (j=0;j<n;j++){
            R[i]+=(M[i][j]*V[j]);
        }
}

完整的功能代码:

void m_mult_v(float** M, float* V, float* R, int m, int n) {

    int i,j;

    for (i=0;i<m;i++){
        for (j=0;j<n;j++) {
            R[i]+=(M[i][j]*V[j]);
        }
    }
}

问题是我得到的结果不正确。 :-/有什么想法吗?

感谢您 future 的回答!

编辑

解决方案已找到,感谢您的提示!

我刚刚添加了这部分代码,将 R 设置为全零。

for (i=0;i<m;i++){
    R[i] = 0;
}

最佳答案

您忘记初始化 R?如果它是堆栈分配的或使用 malloc() 分配的,则其初始状态未定义。

关于c - 矩阵与 vector 相乘,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8553114/

相关文章:

c++ - 我如何能够遍历 C++ 中的字符串 vector ?

c++ - vector 超出范围/范围检查

似乎无法返回字符串

c - 在c中的结构中初始化int类型灵活数组时出错

c - 如何使用 MPI 中的标志打破所有进程中的循环?

c# - 如何将文件中的矩阵读入数组

python - 将表表示为矩阵

c - 为什么 C 数组初始化语法不允许任意赋值?

c++ - 如何修复( 'vector' : undeclared identifier ) in my header file?

r - 将数据帧转换为 R 中的邻接/权重矩阵