【问题标题】:Multiplying a matrix and a vector in C [closed]在C中将矩阵和向量相乘[关闭]
【发布时间】:2012-10-23 05:58:37
【问题描述】:

我想将矩阵和向量相乘,我已经编写了将矩阵和向量存储在 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 行遇到错误,下标值不是数组也不是指针

【问题讨论】:

  • 如果你不能做指针,做数组操作应该更明显。如果你有double* vec,那么你可以访问vec[0]vec[1]等。
  • 一个矩阵乘以一个向量会产生一个向量,而不是一个矩阵,所以你应该只有一个 double *ans = malloc(rows * sizeof (double)); 来保存答案。然后,您可以使用mat[i][j] 访问输入矩阵的每个元素,使用vec[i] 访问输入向量的每个元素,因此只需应用通常的数学来计算答案的每个元素,并将其存储在ans[i] 中。跨度>
  • j_random_hacker 是对的。实际上,函数matrix_vector_multiply 被定义为返回一个双精度数组,因此您尝试生成的结果与函数返回值不兼容(ans 的类型是双精度**,而不是双精度*)。是作业吗?
  • 你是对的,ans 应该是一个向量。我只是做了一些编辑。我会把数学部分放进去,你看看是否正确
  • 我应该添加 return ans;最后?

标签: c arrays 2d malloc


【解决方案1】:

你的函数有几个错误:

  1. for 循环中用于遍历矩阵的变量不应是您传递给函数的参数。尝试这样的事情: for(y=0;y&lt;rows;y++)

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

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

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

希望对您有所帮助, 一月

【讨论】:

  • 嘿 sl,这是我编辑的函数,我认为数学不正确:#include /* 将矩阵乘以向量。 */ double *matrix_vector_multiply(int rows, int cols, double **mat, double *vec) { double *ans = malloc(rows * sizeof (double));诠释我; for (i=0; i
  • 您必须在 for 循环中增加 i 而不是 rows,并且您需要在 for 循环中使用两个变量来进行乘法运算:一个从 0 到 @ 987654329@ 和另一个从0cols-1
猜你喜欢
  • 2021-01-20
  • 1970-01-01
  • 2020-05-03
  • 2021-12-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多