#include <vector>
#include <iostream>
typedef float c_float; // 假设c_float就是float
typedef int c_int; // 假设c_int就是int
int main() {
std::vector<c_float> P_data;
std::vector<c_int> P_indices;
std::vector<c_int> P_indptr;
int col_num = 4; // 矩阵的列数
// 模拟的4x4矩阵,以列为单位存储。每个pair是<行索引, 值>
std::vector<std::vector<std::pair<int, float>>> columns = {
{{0, 1.0}, {1, 5.0}, {2, 9.0}, {3, 13.0}}, // 第一列
{{0, 2.0}, {1, 6.0}, {2, 10.0}, {3, 14.0}}, // 第二列
{{0, 3.0}, {1, 7.0}, {2, 11.0}, {3, 15.0}}, // 第三列
{{0, 4.0}, {1, 8.0}, {2, 12.0}, {3, 16.0}} // 第四列
};
// 用于存储转换后的上三角矩阵
std::vector<std::vector<std::pair<c_int, c_float>>> upper_triangular;
for (size_t col = 0; col < columns.size(); ++col) {
std::vector<std::pair<c_int, c_float>> new_column;
for (const auto& pair : columns[col]) {
if (pair.first <= col) { // 保留上三角部分
new_column.push_back(pair);
}
}
upper_triangular.push_back(new_column);
}
// 打印转换后的矩阵
for (size_t col = 0; col < upper_triangular.size(); ++col) {
std::cout << "第 " << col + 1 << " 列: ";
for (const auto& pair : upper_triangular[col]) {
std::cout << "(" << pair.first << ", " << pair.second << ") ";
}
std::cout << std::endl;
}
int ind_p = 0;
for (int i = 0; i < col_num; ++i) {
P_indptr.push_back(ind_p);
for (const auto& row_data_pair : upper_triangular[i]) {
// 只保留上三角矩阵的元素
P_data.push_back(row_data_pair.second); // 依照题目要求乘以2
P_indices.push_back(row_data_pair.first);
++ind_p;
}
}
P_indptr.push_back(ind_p);
// 打印结果
std::cout << "P_data: ";
for (auto& val : P_data) std::cout << val << " ";
std::cout << "\nP_indices: ";
for (auto& index : P_indices) std::cout << index << " ";
std::cout << "\nP_indptr: ";
for (auto& ptr : P_indptr) std::cout << ptr << " ";
std::cout << std::endl;
return 0;
}
矩阵变成上三角
最新推荐文章于 2024-07-18 16:38:50 发布