下三角矩阵的向量乘法简单实现
#include <iostream>
#include <algorithm>
#include <vector>
#include <chrono>
#include <time.h>
#include <stdio.h>
#include <iomanip>
using namespace std;
//下三角矩阵
const int Row = 4;
const int Col = 4;
float _Matrix[Row][Col];
float vec[Col];
float res[Row];
float* Triangular;
#define DEBUG
void init()
{
Triangular = new float[Row * Col];
for (int i = 0; i < Row; i++)
{
for (int j = 0; j <= i; j++)
{
_Matrix[i][j] = _Matrix[j][i] = rand() % 100;
int t_row = max(i, j);
int t_col = min(i, j);
//下三角矩阵的存储是 max(i, j) * (max(i, j) + 1) / 2 + min(i, j) 是原矩阵下标为(i, j)的元素
Triangular[(t_row + 1) * t_row / 2 + t_col] = _Matrix[i][j];
}
}
for (int i = 0; i < Col; i++)
{
vec[i] = rand() % 100;
}
#ifdef DEBUG
cout << "vec is" << endl;
for (int i = 0; i < Col; i++)
{
cout << vec[i] << ' ';
}
cout << endl;
cout << "this is matrix" << endl;
for (int i = 0; i < Row; i++)
{
for (int j = 0; j < Col; j++)
{
cout << setw(5)<< _Matrix[i][j];
}
cout << endl;
}
#endif
}
void t()
{
float r[Row];
memset(r, 0, sizeof(r));
for (int i = 0; i < Row; i++)
{
for (int j = 0; j < Col; j++)
{
r[i] += _Matrix[i][j] * vec[j];
}
}
#ifdef DEBUG
cout << "result test is " << endl;
for (int i = 0; i < Row; i++)
{
cout << r[i] << ' ';
}
cout << endl;
#endif // DEBUG
}
void triangular(float* v, float* _matrix, int Row, int Col, float* r)
{
for (int row = 0; row < Row; row++)
{
float sum = 0;
for (int col = 0; col < Col; col++)
{
int t_row = max(row, col);
int t_col = min(row, col);
sum += _matrix[(t_row + 1) * t_row / 2 + t_col] * v[col];
}
r[row] = sum;
}
#ifdef DEBUG
cout << "result1 is " << endl;
for (int i = 0; i < Row; i++)
{
cout << r[i] << ' ';
}
cout << endl;
#endif // DEBUG
}
int main()
{
init();
t();
triangular(vec, (float*)Triangular, Row, Col, res);
}
👍