【发布时间】: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;最后?