我想将矩阵和 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 行收到错误,下标值不是数组也不是指针
最佳答案
您的函数中有几个错误:
用于在 for 循环中迭代矩阵的变量不应该是传递给函数的参数。尝试这样的事情:
for(y=0;y<rows;y++)
你必须交换
vec
和mat
在 for 循环中您必须将答案 vector 初始化为
0
(另一个 for 循环)您必须在乘法结束时返回答案 (
return ans;
)
希望有帮助, 一月
关于c - C 中矩阵与 vector 相乘,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13024328/