MichaelE
MichaelE

Reputation: 837

How to create a nxn Unity matrix in Armadillo?

I am trying to use Armadillo for C++. I am using the site for reference: Armadillo Link

The simple and slow way I got it to work was:

arma::mat UnityMatrix = arma:mat(5,5,fill::zeros)
for (int ii = 0; ii < UnityMatrix.n_rows;ii++){
 for (int jj = 0; jj < UnityMatrix.n_cols;jj++){
   if (ii==jj){
     UnityMatrix(ii,jj)=1;
   }
 }

} I create a matrix of zeros, and add ones on the diagonal. This works, but I am sure there is much more efficient way of doing this in Armadillo.

Armadillo has the umat type which should be unity, but I cannot figure out how to use it.

I tried:

arma::umat InitM;
InitM.set_size(5,5);

Which gave me a 5x5 matrix of random values.

When I tried other ways of initializing, but none would compile.

This seems so basic that I cannot find any online examples, but still cannot figure it out.

Upvotes: 2

Views: 2117

Answers (2)

Benjamin Christoffersen
Benjamin Christoffersen

Reputation: 4841

It seems like you want an identity matrix and not a unit matrix from you first example. If you want the former than see the arma::eye<arma::umat>() as suggested by Claes Rolen. For the latter, see you own reply.

As for the question in one of your comments, umat is a matrix with type uword, i.e., unsigned int.

Upvotes: 1

MichaelE
MichaelE

Reputation: 837

I found it right after posting this question. The code is.

arma::mat UnityMatrix = arma:mat(5,5,fill::eye)

With fill::eye being the key. I finally found it when I searched for Identity matrix not Unity matrix.

Upvotes: 2

Related Questions