C++ Armadillo Access Triangular Matrix Elements

帅比萌擦擦* 提交于 2019-12-24 04:11:00

问题


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?

For example with a 5x5 matrix

// 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

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);

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.


回答1:


To check if all the elements in the lower triangle are equal to zero:

bool all_zero = all( X.elem(find(trimatl(X))) == 0 );


来源:https://stackoverflow.com/questions/28969869/c-armadillo-access-triangular-matrix-elements

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!