Skip to content

Solutions

Use these to check your work after you’ve tried the exercises. If something differs, treat it as a debugging opportunity.

Exercise 1

C++:

Eigen::MatrixXd matmul(const Eigen::MatrixXd& A, const Eigen::MatrixXd& B) {
    if (A.cols() != B.rows()) throw std::runtime_error("matmul: incompatible shapes");
    return A * B;
}

Bind:

m.def("matmul", &matmul);

Exercise 2

A[:, ::2] is typically not contiguous (stride changes). That often forces a copy into a contiguous buffer before conversion to Eigen.

Exercise 3

See the shape check in Exercise 1.