====== 002 行列やベクトルの操作 ====== ===== 概要 ===== 行列のメモリ配置の変更方法や、ベクトルの操作についてです。 ==== 行列のメモリ配置変更 ==== 行列はAPIによってメモリ配置(列優先か行優先か)が異なります。例えばOpenGL系は列優先、DirectX系が行優先だったりします。 Eigenではメモリ配置を変えることができます。 void memoryReplaceMatrix() { //デフォルトは ColMajorになっている。 Matrix3f matDefault; Matrix matA; Matrix matB; // カンマオペレータによる初期化はメモリの配置順に依存しない。 matDefault << 1, 2, 3, 4, 5, 6, 7, 8, 9; matA << 1, 2, 3, 4, 5, 6, 7, 8, 9; matB << 1, 2, 3, 4, 5, 6, 7, 8, 9; // メモリの配置順に出力。 for (int i = 0; i < matDefault.count(); ++i) { Log( matDefault(i) ); } for (int i = 0; i < matA.count(); ++i ) { Log( matA(i) ); } for (int i = 0; i < matB.count(); ++i) { Log( matB(i) ); } } ==== 対角行列の作成 ==== void diagonalMatrixVector() { // 対角行列を作成する。 Matrix3f matB; matB << 1, 2, 3, 4, 5, 6, 7, 8, 9; MatrixXf matC = matB.diagonal(); Log(matC); // ベクトルから対角行列を作成する。 Vector3f vec; vec << 1, 2, 3; Matrix3f matA = vec.asDiagonal(); Log(matA); } ==== 転置行列の作成 ==== void transposeMatrix() { Matrix3f matA; matA << 1, 2, 3, 4, 5, 6, 7, 8, 9; Log(matA); Matrix3f matB = matA.transpose(); Log(matB); } ==== 行列の和,積,平均,最小値,最大値,トレース ==== void reductionMatrix() { Matrix3f matA; matA << 1, 2, 3, 4, 5, 6, 7, 8, 9; std::cout << "Sum matA : \n" << matA.sum() << std::endl; std::cout << "Prod matA : \n" << matA.prod() << std::endl; std::cout << "Mean matA : \n" << matA.mean() << std::endl; std::cout << "minCoeff matA : \n" << matA.minCoeff() << std::endl; std::cout << "maxCoeff matA : \n" << matA.maxCoeff() << std::endl; std::cout << "Trace matA : \n" << matA.trace() << std::endl; } ==== 部分的な行や列の和,積,平均,最小値,最大値 ==== void divReductionMatrix() { Matrix3f matA; matA << 1, 2, 3, 4, 5, 6, 7, 8, 9; std::cout << "Sum matA : \n" << matA.rowwise().sum() << std::endl; std::cout << "Prod matA : \n" << matA.rowwise().prod() << std::endl; std::cout << "Mean matA : \n" << matA.rowwise().mean() << std::endl; std::cout << "minCoeff matA : \n" << matA.colwise().minCoeff() << std::endl; std::cout << "maxCoeff matA : \n" << matA.rowwise().maxCoeff() << std::endl; } ==== ベクトルのノルム ==== void NormVector() { Vector3f v; v << 1, 2, 3; std::cout << "v.squaredNorm() = " << v.squaredNorm() << std::endl; std::cout << "v.norm() = " << v.norm() << std::endl; std::cout << "v.lpNorm<1>() = " << v.lpNorm<1>() << std::endl; } ==== 行列のノルム ==== void NormMatrix() { Matrix3f m; m << 1, 2, 3, 4, 5, 6, 7, 8, 9; std::cout << "m.squaredNorm() = " << m.squaredNorm() << std::endl; std::cout << "m.norm() = " << m.norm() << std::endl; std::cout << "m.lpNorm<1>() = " << m.lpNorm<1>() << std::endl; }