构造稀疏矩阵的目的是在处理具有大量零元素的大规模数据时,节省内存空间和计算资源,并提高计算效率。稀疏矩阵是一种特殊的矩阵,其中包含许多零元素和一些非零元素。
#include "pcl.h"
#include "common.h"
#include "optimal_nonrigid_icp.h"
#include <stdio.h>
#include <vector>
#include <iostream>
#include <string>
#include <sstream>
#include <fstream>
#include <cstdio>
#include <stdlib.h>
#include <math.h>
#include <ostream>
#include <iomanip>
#include <algorithm>
#include <Eigen/Sparse>
#include <boost/shared_ptr.hpp>
#include <boost/filesystem.hpp>
using namespace std;
using namespace boost::filesystem;
using namespace Eigen;int main() {// 假设已经定义了适当的变量和数据用于构建稀疏矩阵int n = 3; // 数据点的数量int m = 4; // 某个维度的大小// 创建Triplet对象容器 W_Dstd::vector<Eigen::Triplet<float>> W_D;// 为示例目的,构造一些假设的数据std::vector<double> weights = { 0.1, 0.2, 0.3 };std::vector<std::vector<double>> xyz_values = {{1.0, 2.0, 3.0},{4.0, 5.0, 6.0},{7.0, 8.0, 9.0}};// 循环添加Triplet对象到 W_Dfor (int i = 0; i < n; ++i) {double weight = weights[i];const std::vector<double>& xyz = xyz_values[i];// 添加 Triplet 对象到 W_Dfor (int j = 0; j < 3; ++j)W_D.push_back(Eigen::Triplet<float>(6 * m + i, i * 4 + j, weight * xyz[j]));W_D.push_back(Eigen::Triplet<float>(6 * m + i, i * 4 + 3, weight));}// 构建稀疏矩阵int numRows = 6 * m + n;int numCols = n * 4;Eigen::SparseMatrix<float> sparseMatrix(numRows, numCols);sparseMatrix.setFromTriplets(W_D.begin(), W_D.end());// 输出稀疏矩阵内容std::cout << "Sparse Matrix: " << std::endl << sparseMatrix << std::endl;return 0;
}
其中W_D就是表示稀疏矩阵的非零元素,包含三个成员变量:行索引、列索引和元素值
输出结果:内含权重作用于每个点得到的新值,在每个点的新坐标后存放了权重值(在同一行)
int main()
{int m = 3;int n = 3;float alpha = 1.0f;float gamma = 2.0f;// Construct sparse matrix A with appropriate dimensionsSparseMatrix<float> A(4 * m + n, 4 * n);// Calculate alpha_M_G, representing the non-zero elements of the matrixvector<Triplet<float>> alpha_M_G;// Loop through each edge (m in total) and insert non-zero elementsfor (int i = 0; i < (m - 1); ++i){int a = i;int b = i + 1;// Loop through three axes, insert alpha at specified positionsfor (int j = 0; j < 3; j++){alpha_M_G.push_back(Triplet<float>(i * 4 + j, a * 4 + j, alpha));alpha_M_G.push_back(Triplet<float>(i * 4 + j, b * 4 + j, -alpha));}// Insert alpha * gamma at the fourth coordinate index for vertex a and -alpha * gamma for vertex balpha_M_G.push_back(Triplet<float>(i * 4 + 3, a * 4 + 3, alpha * gamma));alpha_M_G.push_back(Triplet<float>(i * 4 + 3, b * 4 + 3, -alpha * gamma));}// Build sparse matrix AA.setFromTriplets(alpha_M_G.begin(), alpha_M_G.end());// Output sparse matrix Acout << "Sparse Matrix A:" << endl;cout << A << endl;return 0;
}
结果:一个边上的两个顶点a和b决定了alpha的列数,但在同一行,每3行之后获得alpha * gamma和-alpha * gamma(也在同一行)