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 (2/3)

Miscellaneous methods

Is matrix square?

A matrix is 'square' if it has the same number of rows as it does columns:

\[\begin{equation} \begin{bmatrix} 1 & 2 & 3 \\ 4 & 5 & 6 \\ 7 & 8 & 9 \end{bmatrix} \end{equation}\]

Code implementation

This is extremely simple:

def is_square(self):
    return self.size(0) == self.size(1)

Is matrix wide or tall?

If the matrix is not square, then it must either have more columns than rows (wide) or have more rows than columns (tall). We make a couple of methods to test those cases too:

def is_wide(self):
    return self.size(0) < self.size(1)

def is_tall(self):
    return self.size(0) > self.size(1)

Is matrix lower triangular?

Code implementation

We loop over each element in the upper triangular region and if we find a non-zero we return False, otherwise we return True:

def is_lower_tri(self):
    for i, row in enumerate(self.data):
        for col in range(i+1,len(row)):
            if row[col] != 0:
                return False
    else:
        return True

Is matrix upper triangular?

Code implementation

Here we simply call the is_lower_tri method on the transposed matrix:

def is_upper_tri(self):
    return self.tr().is_lower_tri()

Is matrix diagonal?

Code implementation

If the matrix qualifies as both lower and upper, then it must be diagonal. Therefore we use the previous two methods like so:

def is_diag(self):
    if self.is_lower_tri() and self.is_upper_tri():
        return True
    else:
        return False

Is matrix symmetric?

Code implementation

We loop over two ranges - one being the number of rows/columns, and the other being one less than that (since we don't need to check diagonal entries). If we find any $a_{ij} \neq a_{ji}$, we return False, otherwise we return True:

def is_symmetric(self):
    for i in range(self.size(0)):
        for j in range(i+1, self.size(0)):
            if self.ind(i,j) != self.ind(i,j):
                return False
    else:
        return True

< The Mat(rix) Class, generation, and printing

Combining matrices and getting the diagonal >

back to project main page
back to home