c - C 中矩阵与 vector 相乘

标签 c arrays 2d malloc

我想将矩阵和 vector 相乘,我已经编写了将矩阵和 vector 存储在 malloc 数组中的函数。对于这个函数,我需要首先使用 malloc 创建另一个数组来存储我的答案。然后进行计算(http://www.facstaff.bucknell.edu/mastascu/elessonsHTML/Circuit/MatVecMultiply.htm)

#include <stdlib.h>
/* Multiply a matrix by a vector. */
double *matrix_vector_multiply(int rows, int cols,
               double **mat, double *vec){

 // creating an vecotr to hold the answer first

 double *ans= malloc(rows* sizeof(double));

 // do the multiplication:
 mulitply **mat and *vec (mat = the matrix and vec is the vector)

 for (rows=0; rows< ; rows++)
    for (cols=0; cols< ; cols++)
        ans[rows] = ans[rows] + vec[rows][cols] * mat[rows];    

 //not sure if it is right

 // then store the answer back to the ans array            


}

主要功能:

double *matrix_vector_multiply(int rows, int cols,
               double **mat, double *vec);

int main(){
  double *answer = matrix_vector_multiply(rows, cols, matrix, vector);

  printf("Answer vector: \n");
  print_vector(rows, answer);
  return 0;
 }

不知道如何用指针进行乘法然后将其存储回来.. 任何帮助,将不胜感激!谢谢!

编辑:乘法函数:

#include <stdlib.h>
/* Multiply a matrix by a vector. */
double *matrix_vector_multiply(int rows, int cols,
               double **mat, double *vec){

double *ans = malloc(rows * sizeof (double));   
int i;  
for (i=0; i<rows; rows++)
    for (i=0; i<cols; cols++)
        ans[rows] = ans[rows] + vec[rows][cols] * mat[rows];    

return ans;            

}

但我在第 12 行收到错误,下标值不是数组也不是指针

最佳答案

您的函数中有几个错误:

  1. 用于在 for 循环中迭代矩阵的变量不应该是传递给函数的参数。尝试这样的事情: for(y=0;y<rows;y++)

  2. 你必须交换vecmat在 for 循环中

  3. 您必须将答案 vector 初始化为 0 (另一个 for 循环)

  4. 您必须在乘法结束时返回答案 ( return ans; )

希望有帮助, 一月

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

相关文章:

c - 为什么该字符串返回 "@"或弄乱我的 "Z"?

c - 如何在 C 中 malloc array 2d

java - 椭圆形离开小径

c++ - 3d 到 2d 图像转换 - PointCloud 到 OpenCV 图像 - C++

c - 查找某个元素在 c 中重复了多少次

c++ - C++ 命名空间内的外部 "C"链接?

javascript - 在 Javascript 的 For 循环中从另一个数组填充数组

c++ - 从函数 C++ 打印出二维数组

无法打开设备 eth0 : eth0: socket: Invalid argument

javascript - 在 JavaScript 中创建二维数组的方法