Moleson
Moleson

Reputation: 169

Diagonal matrix properly in armadillo

My code works but I'm just curious to see if someone knows how to do this but properly using Armadillo library. Thanks for your time :)

arma::mat W = arma::mat(4, 4, arma::fill::ones);
arma::mat D = arma::mat(4, 4, arma::fill::zeros);

for (size_t i = 0; i < W.n_rows; i++)
{
    for (size_t j = 0; j < W.n_cols; j++)
    {
        D(i, i) += W(i, j);
    }
}
std::cout<< "W = \n"<< W <<std::endl;
std::cout<< "D = \n"<< D <<std::endl;

Upvotes: 0

Views: 1543

Answers (1)

darcamo
darcamo

Reputation: 3493

It seems you are summing the elements in each row in the W matrix and putting the result in the diagonal of the D matrix. That is, you are summing elements over the "columns" dimension. This is very easy to do in armadillo and does not require any manual loop.

Armadillo has a sum function with a few overloads. One of these overloads receives a second parameter that you can use to specify in which dimension you want to perform the sum. Just specify the second dimension (index 1) and you get the proper result.

However, the result you get from arma::sum(W, 1) will be a vector. It makes sense, since you are summing over one of the dimensions of the matrix. Just pass the result to arma::diagmat and you get the same D matrix as with you original code. Your code can then be replaced by

arma::mat W = arma::mat(4, 4, arma::fill::ones);
arma::mat D = arma::mat(4, 4, arma::fill::zeros);

W.print("W");
arma::diagmat(arma::sum(W, 1)).print("D");

Note: I have used the .print method to print the matrices, in case you don't know about it. It is easier to use than using std::cout;

Upvotes: 4

Related Questions