Easy matrix operations with Armadillo

#include <iostream> #include <vector> #include <armadillo> using namespace std; using namespace arma; int main(int argc, char** argv) { vector<vector<double>> v1 = { {1,4,12,2,1}, {7,2,3,1,4}, {5,2,3,1,2}, {3,5,8,2,1} }, v2 = { {2,5,6,8}, {3,12,22,14}, {6,8,19,10}, {11,4,8,7}, {23,15,17,20} }; vector<vector<vector<double>>> all_vectors = {v1,v2}; vector<mat> all_matrices; for(vector<vector<double>> v : all_vectors) { size_t rows = v.size(), cols = v[0].size(); mat temp(rows, cols, fill::zeros); for(size_t i = 0; i < rows; i++) { for(size_t j = 0; j < cols; j++) { temp(i,j) = v[i][j]; } } all_matrices.push_back(temp); } mat A = all_matrices[0], B = all_matrices[1], C = A * B; C.raw_print(cout); return 0; } /* 131 172 355 218 141 147 219 201 91 107 173 145 114 162 313 208 */

Code used to validate the result:

import numpy as np A = np.array([ [1,4,12,2,1], [7,2,3,1,4], [5,2,3,1,2], [3,5,8,2,1] ]) B = np.array([ [2,5,6,8], [3,12,22,14], [6,8,19,10], [11,4,8,7], [23,15,17,20] ]) print(np.dot(A,B)) """ [[131 172 355 218] [141 147 219 201] [ 91 107 173 145] [114 162 313 208]] """

Similarly to Numpy, Armadillo allows us to manipulate matrices easily. Intead of typing repeatedly A(row,col) = val for each value in the matrix, it saves a lot of typing to first initialize a vector and then populate the matrix from it. This library allows us to compute fast with very large matrices and eventually store the results in a file.