Matthew Bennett

Logo

I am a data scientist working on time series forecasting (using R and Python 3) at the London Ambulance Service NHS Trust. I earned my PhD in cognitive neuroscience at the University of Glasgow working with fmri data and neural networks. I favour linux machines, and working in the terminal with Vim as my editor of choice.

View my GitHub Profile

View my LinkedIn Profile

View my CV

Class, standalone functions and miscellaneous methods (3/3)

Combining matrices

This method concatenates two matrices along a dimension.

def cat(A, B, axis=0):
    if axis == 0:
        concatenated = Mat(A.data + B.data)
    elif axis == 1:
        concatenated = Mat([rows[0]+rows[1] for rows in zip(A.data, B.data)])
    return concatenated

Tiling matrices

We can easily make a large matrix by 'tiling' a smaller matrix by a repeated series of concatenations. We make a copy of the original matrix, and in two loops concatenate it to the appropriate axis (starting by adding more columns, and then replicating this 'row of matrices' downwards. (The two loops are identical apart from the axis being specified, and so it's tempting to delete one of them and then loop over the remaining one two times. While this saves 2 lines of code and avoids replicating the loop, it's just a little harder to grasp what's going on. So we go for clarity/readability over brevity):

def tile(self, axes=[1,1]):
    B = dc(self)
    for j in range(axes[1]-1):
        self = cat(self, B, axis=1)
    B = dc(self)
    for i in range(axes[0]-1):
        self = cat(self, B, axis=0)
    return self

Demo

We create a matrix and tile it:

import linalg as la

A = la.Mat([[1, 2],
            [0, 5],
            [0, 0]])

la.print_mat(la.tile(A, [2, 5]))

Outputs:

>>> la.print_mat(la.tile(A, [2, 5]))
[1, 2, 1, 2, 1, 2, 1, 2, 1, 2]
[0, 5, 0, 5, 0, 5, 0, 5, 0, 5]
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
[1, 2, 1, 2, 1, 2, 1, 2, 1, 2]
[0, 5, 0, 5, 0, 5, 0, 5, 0, 5]
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0]

< Is matrix triangular, diagonal, symmetric?

Element-wise functions of one or more matrices >

back to project main page
back to home