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