C ++ Armadillo访问三角矩阵元素 [英] C++ Armadillo Access Triangular Matrix Elements
问题描述
访问Armadillo矩阵的上部或下部三角形元素的最有效方法(即平衡内存和速度)是什么?我知道我可以为元素提供一个整数向量,但是当矩阵变得非常大时,我希望避免携带另一个大向量.还是有一种快速创建上下三角索引的有效方法?
What would be the most efficient (i.e. balance memory and speed) way to access the upper or lower triangular elements of an Armadillo matrix? I know I could provide a vector of integers for the elements but as matrices become very large I would like avoid carrying around another large vector. Or is there an efficient way to quickly create the lower/upper triangular indices?
例如使用5x5矩阵
// C++11 Initialization
arma::mat B = { 1, 2, 3, 4, 5,
6, 7, 8, 9, 10,
11, 12, 13, 14, 15,
16, 17, 18, 19, 20,
21, 22, 23, 24, 25 };
B.reshape(5,5);
// the matrix
//1 6 11 16 21
//2 7 12 17 22
//3 8 13 18 23
//4 9 14 19 24
//5 10 15 20 25
我想在结果向量将位于的下三角形中拉出元素:
I would like to pull the elements in the lower triangle where the result vector would be:
2 3 4 5 8 9 10 14 15 20
我现在唯一想到的解决方案是使用uvec
对象.例如:
The only solution I can think of right now is using a uvec
object. For example:
arma::uvec idx {1,2,3,4,7,8,9,13,14,19);
arma::vec lower_elems = B.elem(idx);
最终对象不必是向量.我只需要能够访问元素以进行各种比较.举一个简单的例子,假设我要检查它们是否都等于0.
The final object doesn't need to be a vector. I just need to be able to access the elements for various comparisons. As a simple example let's say I would want to check if they all equal 0.
推荐答案
要检查下部三角形中的所有元素是否都等于零:
To check if all the elements in the lower triangle are equal to zero:
bool all_zero = all( X.elem(find(trimatl(X))) == 0 );
这篇关于C ++ Armadillo访问三角矩阵元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!