---------------------------------------------------------------------------------------------------------------
This is the basic C++ program of C++ armadillo library which shows how to get the non zero elements of the given matrix of some particular size. It can be carried out by the help of inbuilt function "nonzeros" in armadillo library. It takes one parameter i.e name of input matrix. This function
- Return a column vector containing the non-zero values of X
- X can be a sparse or dense matrix
---------------------------------------------------------------------------------------------------------------
Program::
#include <iostream>
#include <armadillo>using namespace std;
using namespace arma;
int main()
{
//initialize the random generator
//Create a 10 x 10 random matrix and printing it
sp_mat A = sprandu<sp_mat>(10, 10, 0.1); //density=10%
vec a = nonzeros(A); //non zero elements
cout << "Matrix A::\n"<<endl; cout<< A << endl;
cout << "Non zero vector a of Matrix A::\n"<<endl;
cout<< a << endl;
//Create a 10 x 10 random matrix and printing it
mat B(10, 10, fill::eye);
vec b = nonzeros(B); //non zero elements
cout << "Matrix B::\n"<<endl;
cout << B << endl;
cout << "Non zero vector b of Matrix A::\n"<<endl;
cout<< b << endl; return 0;
}
---------------------------------------------------------------------------------------------------------------
Commands to run program on terminal::
$ g++ filename.cpp -o objectname -O2 -larmadillo
$ ./objectname
---------------------------------------------------------------------------------------------------------------
Output::
Matrix A::
[matrix size: 10x10; n_nonzero: 10; density: 10.00%]
(0, 0) 0.7868
(6, 0) 0.2505
(0, 2) 0.7107
(4, 2) 0.9467
(0, 4) 0.0193
(3, 5) 0.4049
(2, 7) 0.2513
(9, 7) 0.0227
(7, 8) 0.5206
(9, 9) 0.3447
Non zero vector a of Matrix A::
0.7868
0.2505
0.7107
0.9467
0.0193
0.4049
0.2513
0.0227
0.5206
0.3447
Matrix B::
1.0000 0 0 0 0 0 0 0 0 0
0 1.0000 0 0 0 0 0 0 0 0
0 0 1.0000 0 0 0 0 0 0 0
0 0 0 1.0000 0 0 0 0 0 0
0 0 0 0 1.0000 0 0 0 0 0
0 0 0 0 0 1.0000 0 0 0 0
0 0 0 0 0 0 1.0000 0 0 0
0 0 0 0 0 0 0 1.0000 0 0
0 0 0 0 0 0 0 0 1.0000 0
0 0 0 0 0 0 0 0 0 1.0000
Non zero vector b of Matrix A::
1.0000
1.0000
1.0000
1.0000
1.0000
1.0000
1.0000
1.0000
1.0000
1.0000
Comments