## With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

No credit card required

# 2.10. Multiplying Matrices

## Problem

You want to turn arrays of arrays of numbers into mathematical matrices, and multiply the matrices together.

## Solution

You can create ` Matrix` objects from arrays of arrays, and multiply them together with the `*` operator:

```	require '
matrix'
require 'mathn'

a1 = [[1, 1, 0, 1],
[2, 0, 1, 2],
[3, 1, 1, 2]]
m1 =
Matrix[*a1]
# =>
Matrix[[1, 1, 0, 1], [2, 0, 1, 2], [3, 1, 1, 2]]

a2 = [[1, 0],
[3, 1],
[1, 0],
[2, 2.5]]
m2 = Matrix[*a2]
# => Matrix[[1, 0], [3, 1], [1, 0], [2, 2.5]]

m1 * m2
# => Matrix[[6, 3.5], [7, 5.0], [11, 6.0]]```

Note the unusual syntax for creating a `Matrix` object: you pass the rows of the matrix into the array indexing operator, not into `Matrix#new` (which is private).

## Discussion

Ruby's `Matrix` class overloads the arithmetic operators to support all the basic matrix arithmetic operations, including multiplication, between matrices of compatible dimension. If you perform an arithmetic operation on incompatible matrices, you'll get an `ExceptionForMatrix::ErrDimensionMismatch`.

Multiplying one matrix by another is simple enough, but multiplying a chain of matrices together can be faster or slower depending on the order in which you do the multiplications. This follows from the fact that multiplying a matrix with dimensions K x M, by a matrix with dimensions MxN, requires K * M * N operations and gives a matrix with dimension K * N. If K is large for some matrix, you can save time by waiting til the end before doing multiplications involving that ...

## With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

No credit card required