スパース行列を構築する目的は、ゼロ要素が多数ある大規模なデータを扱う際に、メモリ空間と計算リソースを節約し、計算効率を向上させることです。スパース行列は、多くのゼロ要素といくつかの非ゼロ要素を含む特別な種類の行列です。
#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_D
std::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_D
for (int i = 0; i < n; ++i) {
double weight = weights[i];
const std::vector<double>& xyz = xyz_values[i];
// 添加 Triplet 对象到 W_D
for (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 はスパース行列を表すゼロ以外の要素で、行インデックス、列インデックス、要素値の 3 つのメンバー変数が含まれます。
出力結果: 各点に適用された内部重みによって取得された新しい値。重み値は各点の新しい座標の後に (同じ行に) 格納されます。
int main()
{
int m = 3;
int n = 3;
float alpha = 1.0f;
float gamma = 2.0f;
// Construct sparse matrix A with appropriate dimensions
SparseMatrix<float> A(4 * m + n, 4 * n);
// Calculate alpha_M_G, representing the non-zero elements of the matrix
vector<Triplet<float>> alpha_M_G;
// Loop through each edge (m in total) and insert non-zero elements
for (int i = 0; i < (m - 1); ++i)
{
int a = i;
int b = i + 1;
// Loop through three axes, insert alpha at specified positions
for (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 b
alpha_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 A
A.setFromTriplets(alpha_M_G.begin(), alpha_M_G.end());
// Output sparse matrix A
cout << "Sparse Matrix A:" << endl;
cout << A << endl;
return 0;
}
結果: 1 つのエッジ上の 2 つの頂点 a と b によってアルファの列数が決まりますが、同じ行では、3 行ごとに alpha*gamma と -alpha*gamma が取得されます (これも同じ行内)