csr格式的稀疏矩阵向量乘法简单实现
#include <iostream>
#include <cstdlib>
#include <immintrin.h>
#include <string.h>
#include <vector>
using namespace std;
const int col = 5;
const int row = 4;
float x[col] = { 1, 2, 3, 4, 5 };//列向量
float res[row];//结果 与行数有关
float orgin[row][col];
//1 2 3 4
//1 2 3 4
//1 2 3 4
//1 2 3 4
int rowIdx[row + 1];
vector<int> colIdx;//所有非0元素对应的列标
vector<float> val;//所有非0元素
void init()
{
for (int i = 0; i < row; i++)
{
rowIdx[i + 1] = rowIdx[i];
for (int j = 0; j < col; j++)
{
orgin[i][j] = j + 1;//1 2 3 4
if (j == 2)orgin[i][j] = 0;
if (orgin[i][j] != 0)
{
rowIdx[i + 1] += 1;
val.push_back(orgin[i][j]);
colIdx.push_back(j);
}
}
}
}
//稀疏矩阵向量乘法x为列向量,val,colIdx, rowIdx为csr格式的矩阵压缩
void smmSerial(int numRows,vector<float>& val, vector<int>& colIdx, int* rowIdx, float* x, float* res)
{
for (int i = 0; i < numRows; i++)
{
int start = rowIdx[i];
int end = rowIdx[i + 1];
//第i行的矩阵在val的下标是[start,end - 1]
//对应的列标号是rowIdx[j]
float sum = 0;
for (int j = start; j < end; j++)
{
sum += val[j] * x[colIdx[j]];
}
res[i] = sum;//每次循环可以计算出一个结果
}
for (int i = 0; i < numRows; i++)
{
cout << res[i] << ' ';
}
}
int main()
{
init();
smmSerial(row, val, colIdx, rowIdx, x, res);
}