FYS3150/FYS4150 course material

Introduction to armadillo, introduction to armadillo #.

Armadillo is an efficient linear algebra library for C++, that balances speed and ease of use. We recommend using this library for numerical linear algebra computations in this course.

Weโ€™ll cover some of the very basics of Armadillo here to get you started with the library. A complete overview of the available classes and functions, along with usage examples, can be found in the Armadillo code documentation .

Building code with Armadillo #

We must make sure to include the header file for Armadillo, which amounts to adding #include <armadillo> at the top of a header or source file.

Compiling code with Armadillo #

For macOS users specifically, you must specificy a version of C++ that is C++11 or later. This is done by adding the compiler flag -std=c++11 during compilation.

For Linux users, nothing special is typically required.

Linking code with Armadillo #

To link to Armadillo, we must add the compiler flag -larmadillo during linking.

Armadillo provides a useful vector class arma::vec that can be used to replace arrays in numerical computations. Assume n is a positive integer.

Declaring and filling vectors #

Accessing and assigning elements in a vector #.

We can access an element i from a vector x by

We can assign a new value to element i in the vector x using

Assume that n and m are positive integers.

Declaring and filling matrices #

Creating matrices with Armadillo is easy. Hereโ€™s a couple examples:

Accessing elements in a matrix #

Access of elements in an Armadillo matrix is done as follows:

Extracting a column of a matrix #

Armadillo provides a simple way to extract entire columns of a matrix:

Read matrix columns in a given order #

A particular task that may be useful in this course is to read the columns of a matrix in a specific order. Below is an example that uses arma::sort_index to find the index ordering that sorts a given vector (from low to high values), and then sorts both the vector and the columns of a matrix according to this ordering.

Saving and loading vectors and matrices #

Armadillo provides built-in functionality for saving and loading arma::vec and arma::mat objects to binary files. Not only does this simplify storage of results with a predictable format, but it turns out that they provide a Python module pyarma that can me used to load in these objects directly into a Python program!

If A is an arma::mat object, you can save it using

The default storage format is binary. Your filename should end with .bin . Loading the object is as simple as

Reading a data table in text format #

The load functionality in Armadillo can also be used to load data from files not generated by Armadillo, as long as the data file has some standard format (see the Armadillo documentation for details). For instance, assume we have a text file mynumbers.dat looking like this:

To read these numbers into an Armadillo matrix, we simply do this:

The Python module #

You can install the Armadillo Python module pyarma using

The recommended way to import the library in Python is

From there, you can easily load the arma::mat (or arma::vec ) object you saved in C++ using

Assignment Operations on Matrices

Learn how to assign matrices using R, Rcpp, Armadillo, and Eigen libraries.

What is a matrix?

Explanation, matrix visualization, matrix assignment in rcpp, matrix assignment in armadillo, matrix assignment in eigen.

Matrix ๐ด ๐ด A of dimension ( ๐‘š ร— n ) (๐‘š \times n) ( m ร— n ) is an ( ๐‘š ร— ๐‘› ) (๐‘š \times ๐‘›) ( m ร— n ) collection of elements. The elements are ordered according to a rectangular scheme consisting of ๐‘š ๐‘š m rows and ๐‘› ๐‘› n columns, such as:

[ a 11 a 12 โ€ฆ a 1 n a 21 a 22 โ€ฆ a 2 n โ‹ฎ โ‹ฎ โ‹ฎ โ‹ฎ a m 1 a m 2 โ€ฆ a m n ] \begin{bmatrix} a_{11} & a_{12} & \dots & a_{1n} \\ a_{21} & a_{22} & \dots & a_{2n} \\ \vdots & \vdots & \vdots & \vdots\\ a_{m1} & a_{m2} & \dots & a_{mn} \end{bmatrix} โŽฃ โŽก โ€‹ a 11 โ€‹ a 21 โ€‹ โ‹ฎ a m 1 โ€‹ โ€‹ a 12 โ€‹ a 22 โ€‹ โ‹ฎ a m 2 โ€‹ โ€‹ โ€ฆ โ€ฆ โ‹ฎ โ€ฆ โ€‹ a 1 n โ€‹ a 2 n โ€‹ โ‹ฎ a mn โ€‹ โ€‹ โŽฆ โŽค โ€‹

Here, ๐‘Ž ๐‘– ๐‘— ๐‘Ž_{๐‘–๐‘—} a ij โ€‹ , with ๐‘– = 1 , . . . , ๐‘š ๐‘– = 1,...,๐‘š i = 1 , ... , m and ๐‘— = 1 , . . . , ๐‘› ๐‘— = 1,...,๐‘› j = 1 , ... , n .

Matrix assignment in R

In base R, the matrix() function instantiates the matrix passing the data and the dimensions, and determines whether the matrix is filled by columns (which is the default) or by rows.

In the code above:

Lines 1โ€“5 : We use the matrix() function to create a matrix of dimensions ( 2 ร— 3 ) (2 \times 3) ( 2 ร— 3 ) .

Line 7: We use the class() function to return the values of the class attribute of an R object.

Line 8: We use the dim() function to print the dimensions of the matrix.

Lines 9โ€“10: The nrow() and ncol() functions print the number of rows and the number of columns in the matrix, respectively.

The returned object is of class matrix of dimension ( 2 ร— 3 ) (2 \times 3) ( 2 ร— 3 ) , that is, 2 2 2 rows and 3 3 3 columns.

[ 1 2 3 4 5 6 ] \begin{bmatrix} 1 & 2 & 3 \\ 4 & 5 & 6 \\ \end{bmatrix} [ 1 4 โ€‹ 2 5 โ€‹ 3 6 โ€‹ ]

According to data science professionals, the first step in studying data is visualization. It is the same for matrix algebra. It is important for us to determine what structure the data uses. If we use the plot.matrix package, the matrix can be visualized as a heatmap.

Letโ€™s try executing the following code to display a randomly distributed heatmap.

In the example above, the matrix has no structure because it has been constructed randomly, drawing its elements from a uniform distribution.

The diagonal matrix below uses a diagonal data structure instead:

In both of the example codes above:

Line 2: Weโ€™ve defined the color spectrum of the heatmap in pal .

Line 5: The runif() method is used to create random deviates of the uniform distribution.

Line 8: The png() method saves the output graph as graph.png and the plot() function displays the result.

Line 9: We use the par() function to define the margins.

In Rcpp, there are matrix classes for different data types:

  • LogicalMatrix
  • IntegerMatrix
  • NumericMatrix
  • ComplexMatrix
  • CharacterMatrix
Note: Throughout this course, we use the NumericMatrix class.

The next code example works similarly to the matrix function above. We need to do a little bit of work to implement byrow = TRUE because in Rcpp thereโ€™s no native assignment method by row. This lack of assignment is probably due to the fact that Rcpp is an interface between R and C++, and in C++, matrices are column-major. (This refers to how matrix data is stored in computers.)

Note: The main.cpp file contains the algorithm for the assignment operation. The main.r file implements the algorithm.

Now, the Rcpp function can be tested in the same R use case by inserting matrix elements. First, weโ€™ll insert elements by column.

[ 1 3 5 2 4 6 ] \begin{bmatrix} 1 & 3 & 5 \\ 2 & 4 & 6 \\ \end{bmatrix} [ 1 2 โ€‹ 3 4 โ€‹ 5 6 โ€‹ ]

Then we will insert elements by row.

Armadillo provides a matrix template class, but for the sake of simplicity, weโ€™ll use typedef mat = Mat<double> throughout the course.

Armadillo has a matrix constructor that takes a vector and the requested matrix dimensions as inputs. Also, thereโ€™s no built-in method for assignment by row in Armadillo. Therefore, this case needs a little bit of additional work.

Now, the mat_assign_A() function can be tested in the same R use case by inserting matrix elements. Again, first weโ€™ll test by column:

Note: Writing a matrix like: c(1, 2, 3, 4, 5, 6), 2, 3, 0) or: c(1, 2, 3, 4, 5, 6), nrow = 2, ncol = 3, bycol = 0) is a personal choice. Both statements mean that a ( 2 ร— 3 ) (2 \times 3) ( 2 ร— 3 ) matrix is made.

And next, weโ€™ll test by row:

Eigen provides a matrix template class, but to keep it simple, weโ€™ve used the double data type class in this course with Dynamic dimensions defined as the following:

typedef Matrix<double, Dynamic, Dynamic> MatrixXd

Eigen uses an insertion operator ( ยซ ) to assign a vector to a matrix by column. In the assignment function implementation below, elementwise assignment is used to manage the by row case.

Now, we can test the Eigen function mat_assign_E() in the same R use case by inserting matrix elements. First, weโ€™ll look at this by column:

And then weโ€™ll look at it again by row:

You are using an outdated browser. Please upgrade your browser to improve your experience.

Solarian Programmer

My programming ramblings, getting started with armadillo a c++ linear algebra library on windows, mac and linux, posted on march 24, 2017 by paul.

In this article, I will give you a quick introduction in how to get started with Armadillo , a C++ Matlab like Linear Algebra Library on Windows, Mac and Linux. Armadillo is particularly interesting for Matlab users that want to port their code to C++ for speed. Please note that Armadillo is not a drop in replacement for all Matlab functionality. If your code uses some specialized Matlab toolbox, you will need to find another library to complement Armadillo or implement the missing functionality from scratch.

Armadillo uses BLAS and LAPACK for matrix operations. It is recommended that you install an optimized version of the above libraries on your system and not the reference implementations from Netlib . I will guide you on how to install accelerated versions of BLAS and LAPACK for your operating system, in the install sections of this article.

Simple Armadillo test program:

Letโ€™s start with a simple example of using Armadillo. Please note the Matlab like high level syntax:

This is the result of the above code on my machine:

If you need to transfer data between Matlab and Armadillo check my other Armadillo article .

If you want to have a taste of how elaborate is to directly use functions from BLAS or LAPACK , check the documentation for the reference implementation of SGEMM which performs matrix-matrix multiplication. Alternatively, you can check Intelโ€™s documentation page for their C wrapper for SGEMM .

Next, go to the section that matches your OS: Windows , Mac or Linux .

Windows installation:

I assume that you have latest stable version of Visual Studio installed, currently this is 2017, and that you can create, compile and execute a simple C++ code from the IDE. If you canโ€™t find the C++ project template when you open VS, make sure to install the C++ support. In the latest versions of VS, this is not installed by default.

On Windows, I would recommend using Intel MKL if you have an Intel processor or OpenBlas which works on both Intel and AMD processors. Both alternatives provide Windows binaries and the usage is similar, you need to link the libraries to your compiled code. I will exemplify the process using Intel MKL, which I personally prefer.

Intel MKL can be freely obtained from the above link, by creating an Intel account. After registration, you will be able to download an installer which will copy the libraries, typically in C:\Program Files (x86)\IntelSWTools . Open IntelSWTools and find the mkl folder. For example, on my machine, I found mkl in IntelSWT โ†’ compilers_and_libraries_xxxxx โ†’ windows .

Next, create a new Visual C++ โ†’ Win32 Console Application project. Be sure to select Empty Project , like in the next image:

Visual Studio 2017 C++ Win32 Console Project Settings

Right click on the Source Files line and add a C++ source file. I named this main.cpp , but you can use any name you want:

Visual Studio 2017 C++ add main.cpp file

Now, open the project folder. By default, VS will save new projects in Documents โ†’ Visual Studio 2xxx โ†’ Projects . Iโ€™ve named my project Armadillo_demo , so I will open this folder. Copy the mkl folder in your project folder.

Download the stable version of Armadillo from http://arma.sourceforge.net/download.html , at the time of this writing this is armadillo-7.800.2.tar.xz . Extract the archive, Iโ€™ve used 7zip for this. Once the archive is extracted. open the armadillo-xxx folder and copy the include folder in your project folder, like you did with mkl . Iโ€™ve put the include folder in my project folder inside a new folder named armadillo .

If youโ€™ve followed my instructions, you should have something like this in your project folder:

Visual Studio 2017 project folder content

Please note that armadillo from the above image contains the include folder from armadillo-xxx .

You can fine tune Armadillo, by modifying config.hpp from armadillo โ†’ include โ†’ armadillo_bits. For the purposes of this tutorial, weโ€™ll keep the defaults. As a side note, config.hpp is a header file, so you can modify it at any time, preferably when you have more experience with Armadillo.

The reason Iโ€™ve directed you to copy the above folders in your project folder, is to have a self contained project. Basically, you will be able to move the project on a different computer that has VS installed and use the project as it is.

In the future, if you need/want to update Armadillo, simply replace the files from the above include folder.

First open the project in VS, if it is not already opened. Right click on the project name and select Properties . Unfold the C/C++ list and select General โ†’ Additional Include Directories , double click and select Edit . Use the yellow button to insert a new line and browse for mkl\include in your project folder and press Select folder . Click on the path line and replace everything until \mkl\include with two dots. You should have something like ..\mkl\include . Repeat the above steps for armadillo\include . You should end up with something like:

Visual Studio 2017 Armadillo project include folders

Next, click on Linker โ†’ General โ†’ Additional Import Library and select mkl\lib\intel64_win . In the unlikely case that your computer or Windows is 32 bits, use mkl\lib\ia32_win . Like before, erase the first part of the path and replace it with two dots. You should end up with something like:

Visual Studio 2017 Armadillo project libraries folders

Now, click on Linker โ†’ Input โ†’ Additional Dependencies , click on the existing line and select Edit . Add three new entries: mkl_core.lib , mkl_sequential.lib , mkl_intel_lp64.lib :

Visual Studio 2017 project adding Intel MKL

Press OK on the above window. Press Apply and OK on the Properties window.

Now, copy the Armadillo example from the beginning of this article, in your main.cpp file.

Change the compiler to x64 :

Visual Studio 2017 Armadillo C++ project select x64 compiler

Now, build and run the code by pressing Debug โ†’ Start Without Debugging . You should see something like this:

Visual Studio 2017 Armadillo project results

Mac installation:

On Mac, first make sure that you have the latest versions of Xcode and Command Line Tools installed. You can install Xcode from the AppStore application. If you donโ€™t have the Command Line Tools installed, open a Terminal and type:

which will guide you through the installation process.

Once Xcode is installed, open the application and accept the license (without this, some people reported strange errors).

Next, install Homebrew , which is a nice package manager that will let you install various software from your Terminal. Just follow the installation instructions from their web page and accept the defaults.

Go to the Armadillo web page and check the version number of the stable version. Usually, Homebrew has the latest version of Armadillo available. If this is not the case you can install from sources.

Open a Terminal and type:

If the version number for Armadillo reported by Homebrew , corresponds to the stable version from the library web page, all is good. You can install the library with:

If the Hombrew version is older than the latest stable version of Armadillo , download the library and extract the archive in your Downloads folder. In order to compile Armadillo from sources, open a Terminal and write:

At this point, you should have Armadillo installed on your machine. On Mac, there is no need to install BLAS and LAPACK , the system already provides accelerated versions of these libraries and Armadillo will use them.

First, I will show you how to compile the example from the beginning of this article, using the Terminal. Copy the code in a file named test.cpp and write:

Running the above commands on my machine:

Mac compiling and running the Armadillo example in Terminal

Next, open Xcode and create a new macOS, Command Line Tool project. Give the project a name, something like Armadillo_demo . Make sure that you select C++ for the Language :

Xcode C++ Armadillo new project settings

press Next and accept the defaults for the remaining options.

In the left panel, click on the project name and select the Build Settings tab. Next, use the search box to find the compiler search paths for headers and libraries. Click on the Header Search Paths and add /usr/local/include . Repeat for the Library Search Paths and add /usr/local/lib :

Xcode update search paths

Next, select the Build Phases tab โ†’ Link Binary With Libraries , press + and select Add Other . Now, press Command + Shift + G which will open a search text box, write /usr/local and press Go . Select the lib folder and libarmadillo.dylib . Press Open to finish:

Xcode add libarmadillo.dylib to the project

An alternative approach to add the library, is to use the Terminal to navigate to /usr/local/lib . Open Finder directly in /usr/local/lib and simply drag the library file libarmadillo.dylib in Xcode:

Now, copy the Armadillo example from the beginning of this article, to your main.cpp file and press the run button:

Xcode running the Armadillo example

Linux installation:

I will use Ubuntu 16.04 LTS to exemplify the Linux installation.

Open a Terminal and make sure that your system is updated:

Next, weโ€™ll install Armadillo prerequisites:

Theoretically, you can install Armadillo using the apt package manager, but this is not recommended because the version provided by apt is really old. I suggest to download and extract the latest stable release of Armadillo . Once you have Armadillo extracted in your Downloads folder, you can build and install the library with:

Now, copy the Armadillo example from the beginning of this article, to a file named test.cpp . You can compile the code using:

Running the code on my system:

Running the Armadillo example on Ubuntu 16.04

If you are interested to learn more about the new C++11/C++14 syntax, I would recommend reading The C++ Programming Language by Bjarne Stroustrup.

armadillo matrix assignment

or, Professional C++ by M. Gregoire, N. A. Solter, S. J. Kleper:

armadillo matrix assignment

Navigation Menu

Search code, repositories, users, issues, pull requests..., provide feedback.

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly.

To see all available qualifiers, see our documentation .

  • Notifications You must be signed in to change notification settings

summary page for Armadillo - https://arma.sourceforge.net

conradsnicta/armadillo

Folders and files, repository files navigation, armadillo - c++ library for linear algebra & scientific computing.

status

Download latest version

Documentation (with code examples)

Bug reports and frequently asked questions

Source code repo (GitLab)

Fast C++ matrix library with easy to use functions and syntax, deliberately similar to Matlab. Uses template meta-programming techniques.

Also provides efficient wrappers for LAPACK, BLAS and ATLAS libraries, including high-performance versions such as Intel MKL, AMD ACML and OpenBLAS.

Useful for machine learning, pattern recognition, signal processing, bioinformatics, statistics, finance, etc.

  • Easy to use
  • Many MATLAB like functions
  • Efficient classes for vectors, matrices, cubes (3rd order tensors) and fields
  • Fast singular value decomposition (SVD), eigen decomposition, QR, LU, Cholesky, FFT
  • Statistical modelling using Gaussian Mixture Models (GMM)
  • Clustering using K-means and Expectation Maximisation
  • Automatic vectorisation of expressions (SIMD)
  • Contiguous and non-contiguous submatrices
  • Automatically combines several operations into one
  • Useful for prototyping directly in C++
  • Useful for conversion of research code into production environments
  • Conrad Sanderson
  • Ryan Curtin

NOTE: please see the Questions page before contacting the developers

Related Projects

  • ensmallen - fast non-linear numerical optimisation library
  • mlpack - extensive library of machine learning algorithms
  • PyArmadillo - linear algebra library for Python with Matlab-like syntax
  • CARMA - bidirectional interface between Python and Armadillo

COMMENTS

  1. Armadillo: C++ library for linear algebra & scientific ...

    Generate a scalar, vector, matrix or cube with the elements set to random values with normal / Gaussian distribution, parameterised by mean mu and standard deviation sd. The default distribution parameters are mu = 0 and sd = 1. For complex elements, the real and imaginary parts are treated separately.

  2. Armadillo C++: How to make effcient assignment to submat

    I want to assign the value of a matrix to the submat of another matrix as A.submat(ni1, ni2, nk1, nk2) = B; It seems very slow. I'm wondering why it's so slow, and is there some way to improve it?

  3. Super C++ optimization of matrix multiplication with Armadillo

    I'm using Armadillo to do very intensive matrix multiplications with side lengths $2^n$, where $n$ can be up to 20 or even more. I'm using Armadillo with OpenBLAS for matrix multiplication, which s...

  4. Introduction to Armadillo — FYS3150/FYS4150 course material

    Armadillo provides a simple way to extract entire columns of a matrix: arma::vec col_vec = A.col(j); //Extract column j of A and assign it to col_vec. Read matrix columns in a given order. A particular task that may be useful in this course is to read the columns of a matrix in a specific order.

  5. GitHub - dendisuhubdy/armadillo: C++ Linear Algebra Library

    Armadillo is a high quality C++ library for linear algebra and scientific computing, aiming towards a good balance between speed and ease of use. It's useful for algorithm development directly in C++, and/or quick conversion of research code into production environments. The syntax (API) is deliberately similar to Matlab.

  6. Assignment Operations on Matrices - Computing Matrix Algebra ...

    Matrix assignment in Armadillo. Armadillo provides a matrix template class, but for the sake of simplicity, we’ll use typedef mat = Mat<double> throughout the course. Armadillo has a matrix constructor that takes a vector and the requested matrix dimensions as inputs. Also, there’s no built-in method for assignment by row in Armadillo.

  7. Armadillo: C++ library for linear algebra & scientific computing

    Armadillo is a high quality linear algebra library (matrix maths) for the C++ language, aiming towards a good balance between speed and ease of use. Provides high-level syntax and functionality deliberately similar to Matlab.

  8. Armadillo: a template-based C++ library for linear algebra

    Armadillo provides efficient objects for vectors, matrices and cubes (third order tensors), as well as over 200 associated functions for manipulating data stored in the objects. Integer, floating point and complex numbers are supported, as well as dense and sparse storage formats.

  9. Getting started with Armadillo a C++ Linear Algebra Library ...">Getting started with Armadillo a C++ Linear Algebra Library ...

    Armadillo uses BLAS and LAPACK for matrix operations. It is recommended that you install an optimized version of the above libraries on your system and not the reference implementations from Netlib .

  10. GitHub - conradsnicta/armadillo: summary page for Armadillo ...">GitHub - conradsnicta/armadillo: summary page for Armadillo ...

    Fast C++ matrix library with easy to use functions and syntax, deliberately similar to Matlab. Uses template meta-programming techniques. Also provides efficient wrappers for LAPACK, BLAS and ATLAS libraries, including high-performance versions such as Intel MKL, AMD ACML and OpenBLAS.