gpt4 book ai didi

c++ - 矩阵 vector 乘法 CCS c++

转载 作者:行者123 更新时间:2023-11-30 05:30:45 25 4
gpt4 key购买 nike

我正在尝试将一个矩阵和一个 vector 与 Compressed Column Storage 中的矩阵相乘.矩阵是:

0   3   0   
4 0 0
2 0 0

这是 CCS 表格:

[ 4 2 3 ]
[ 2 3 1 ]
[ 1 3 4 4 ]

vector 是:

[ 1 3 4 ]

所以产品应该是

[ 9 4 2 ]

这是我要创建的函数

vector<int> multiply(vector<int> val,vector<int> col,vector<int> row,vector<int> v, int r){

vector<int> x(v.size());
for (int j=0; j<r; j++) {
for (int i=col[j]-1; i<col[j+1]-1; i++) {
cout<<"\n"<<val[i]<<"*"<<v[j]<<"\n";
x[j]+= val[i]*v[j];
}
}
return x;
}

但这会返回

[ 6 9 0 ]

这是我最接近真正的解决方案,我该如何解决这个问题?

最佳答案

我认为这是由 col_ptr vector 驱动的。

1.) 我不确定 r 可以取什么值,所以我删除了它,因为我们不需要这些信息来解决问题2.) 我应该注意到我没有编译这个,但我相信算法是正确的3.) 有一些明显的方法可以优化此代码的内存使用,但我保留了这些变量以帮助解释该过程。4.) 您发布的代码的主要问题是它似乎没有使用行数组来告诉我们值在哪一行!

vector<int> multiply(vector<int> val,vector<int> col,vector<int> row,vector<int> v) {
vector<int> x(v.size());
//we may need to initialize x as all zeroes, I forget
int col_size = col.size();
int column_idx = 0;
for (int j=0; j<col_size-1; j++) {
//j indicates where the columns start going!
//columns end prior to the next column start
//val_index is where we need to start in the val array, for this column
int val_index_start = col[j]-1; //this is redunda
//we keep traversing forward until the next column starts
int next_column_start = col[j+1]-1;
for (int k=val_index_start; k < next_column_start && k < v.size(); k++) {
int row_of_cell = row[k] - 1;
int column_of_cell = column_idx;
int product = v[column_idx]*val[k];
x[row_of_cell] += product;
}
column_idx++;
}
return x;
}

关于c++ - 矩阵 vector 乘法 CCS c++,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35835496/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com