# API Showcase

Here are some examples of Eigen 3's API. Refer to the documentation for more details.

## Contents

## Performing row/column operations on a matrix

Let m be a matrix. All the following operations are allowed by Eigen, with the self-explanatory effect, and resulting in fully optimized code.

m.row(i) += alpha * m.row(j); m.col(i) = alpha * m.col(j) + beta * m.col(k); m.row(i).swap(m.row(j)); m.col(i) *= factor;

## Operating on blocks inside a matrix or vector

m.block(firstRow, firstCol, rows, cols).setZero(); m.topLeftCorner(rows, cols) = some_other_matrix; m.block<2,2>(firstRow, firstCol).setIdentity(); // optimized variant when the # of rows, cols are known at compile-time

There are also vector-specific operations. Let v be a vector.

v.segment(first, size) = some_other_vector; v.segment<3>(position1) = v.segment<3>(position2); // optimized variant when the size is known at compile-time v.head(n).setConstant(12); // writes 12 in the n first coefficients of v m.diagonal().tail(n) *= lambda; // multiplies by lambda the n last diagonal coefficients of a matrix m

## Computing sums

result = m.sum(); // returns the sum of all coefficients in m result = m.row(i).sum(); result = m.rowwise().sum(); // returns a vector of the sums in each row

Here is how you would compute the sum of the cubes of the i-th column of a matrix:

result = m.col(i).array().cube().sum(); // array() returns an array-expression

## Comma-initializer

Like other libraries, Eigen has a comma-initializer allowing to construct a matrix like this:

Matrix3f m; m << 1, 2, 3, 4, 5, 6, 7, 8, 9;

Unlike other libraries, Eigen's comma-initializer can be combined at will with expressions, which makes it very powerful. See our tutorial on this subject.

## Linear solving

Just choose the matrix decomposition that you want, the solve() API is the same everywhere. Thus, switching decompositions is very easy. In just one line of code, you can decompose and solve.

result = m.lu().solve(right_hand_side); // using partial-pivoting LU result = m.fullPivLu().solve(right_hand_side); // using full-pivoting LU result = m.householderQr().solve(right_hand_side); // using Householder QR result = m.ldlt().solve(right_hand_side); // using LDLt Cholesky

See this tutorial page for more information about solving.