Matrices

This section covers notes on matrices. The matrix ADT is a multidimensional array. Importantly, matrices are contrasted from jagged arrays.

Here's a simple matrix:

012012123456789

This is a 3×3{3 \times 3} matrix. We can perform several operations on matrices.

Matrix Addition

Matrix addition can be implemented as follows:

matrix_add(matrix_a: number[][], matrix_b: number[][]) {
	const output: number[][] = [];
	for (let i = 0; i < matrix_a.length; i++) {
		const row: number[] = [];
		for (let j = 0; j < matrix_a[i].length; j++) {
			const result = matrix_a[i][j] + matrix_b[i][j];
			row.push(result);
		}
		output.push(row);
	}
	return output;
}

Matrix Subtraction

Matrix subtraction takes a similar form:

matrix_sub(matrix_a: number[][], matrix_b: number[][]) {
	const output: number[][] = [];
	for (let i = 0; i < matrix_a.length; i++) {
		const row: number[] = [];
		for (let j = 0; j < matrix_a[i].length; j++) {
			const result = matrix_a[i][j] - matrix_b[i][j];
			row.push(result);
		}
		output.push(row);
	}
	return output;
}

Matrix Multiplication

And here is multiplication:

matrix_mul(matrix_a: number[][], matrix_b: number[][]) {
	const output: number[][] = [];
	for (let i = 0; i < matrix_a.length; i++) {
		const row: number[] = [];
		for (let j = 0; j < matrix_a[i].length; j++) {
			const result = matrix_a[i][j] * matrix_b[i][j];
			row.push(result);
		}
		output.push(row);
	}
	return output;
}

Matrix Division

Division:

matrix_div(matrix_a: number[][], matrix_b: number[][]) {
	const output: number[][] = [];
	for (let i = 0; i < matrix_a.length; i++) {
		const row: number[] = [];
		for (let j = 0; j < matrix_a[i].length; j++) {
			const result = matrix_a[i][j] / matrix_b[i][j];
			row.push(result);
		}
		output.push(row);
	}
	return output;
}