矩阵变成上三角

#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;
}

  • 3
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值