Common Matrix Operations
Part of the Logic & Flow section of Coddy's C# journey — lesson 6 of 66.
Matrices are commonly used in mathematics and computer science. Let's explore some common operations on 2D arrays.
Add two matrices together:
int[][] AddMatrices(int[][] a, int[][] b)
{
int rows = a.Length;
int[][] result = new int[rows][];
for (int i = 0; i < rows; i++)
{
result[i] = new int[a[i].Length];
for (int j = 0; j < a[i].Length; j++)
{
result[i][j] = a[i][j] + b[i][j];
}
}
return result;
}Transpose a matrix (swap rows and columns):
int[][] Transpose(int[][] matrix)
{
int rows = matrix.Length;
int cols = matrix[0].Length;
int[][] result = new int[cols][];
for (int i = 0; i < cols; i++)
{
result[i] = new int[rows];
for (int j = 0; j < rows; j++)
{
result[i][j] = matrix[j][i];
}
}
return result;
}Calculate the sum of each row:
int[] RowSums(int[][] matrix)
{
int rows = matrix.Length;
int[] sums = new int[rows];
for (int i = 0; i < rows; i++)
{
int sum = 0;
for (int j = 0; j < matrix[i].Length; j++)
{
sum += matrix[i][j];
}
sums[i] = sum;
}
return sums;
}Multiply two matrices together:
In matrix multiplication, each element
result[i][j] is computed as the dot product of row i from the first matrix and column j from the second matrix — that is, the sum of matrix1[i][k] * matrix2[k][j] for every k. The first matrix must have as many columns as the second matrix has rows.int[][] MultiplyMatrices(int[][] a, int[][] b)
{
int rows = a.Length;
int cols = b[0].Length;
int inner = b.Length;
int[][] result = new int[rows][];
for (int i = 0; i < rows; i++)
{
result[i] = new int[cols];
for (int j = 0; j < cols; j++)
{
int sum = 0;
for (int k = 0; k < inner; k++)
{
sum += a[i][k] * b[k][j];
}
result[i][j] = sum;
}
}
return result;
}Challenge
HardCreate a method called multiplyMatrices that:
- Takes two matrices (2D jagged arrays) as parameters: matrix1 and matrix2
- Multiplies them following the rules of matrix multiplication
- Returns the resulting matrix
For matrix multiplication to be valid:
- The number of columns in matrix1 must equal the number of rows in matrix2
- The result will have dimensions: [matrix1.rows × matrix2.columns]
How matrix multiplication works:
Each element at position [i][j] in the result is computed by taking row i from matrix1 and column j from matrix2, multiplying their corresponding elements together, and summing all those products:result[i][j] = matrix1[i][0] * matrix2[0][j] + matrix1[i][1] * matrix2[1][j] + ...
In other words: result[i][j] = sum of (matrix1[i][k] * matrix2[k][j]) for each k.
For example, if matrix1 is:
[1, 2]
[3, 4]And matrix2 is:
[5, 6]
[7, 8]Then result[0][0] = 1*5 + 2*7 = 19, result[0][1] = 1*6 + 2*8 = 22, and so on. The result should be:
[19, 22]
[43, 50]If the matrices cannot be multiplied, return null.
Cheat sheet
Common matrix operations using 2D jagged arrays:
Add two matrices:
int[][] AddMatrices(int[][] a, int[][] b)
{
int rows = a.Length;
int[][] result = new int[rows][];
for (int i = 0; i < rows; i++)
{
result[i] = new int[a[i].Length];
for (int j = 0; j < a[i].Length; j++)
{
result[i][j] = a[i][j] + b[i][j];
}
}
return result;
}Transpose a matrix (swap rows and columns):
int[][] Transpose(int[][] matrix)
{
int rows = matrix.Length;
int cols = matrix[0].Length;
int[][] result = new int[cols][];
for (int i = 0; i < cols; i++)
{
result[i] = new int[rows];
for (int j = 0; j < rows; j++)
{
result[i][j] = matrix[j][i];
}
}
return result;
}Calculate the sum of each row:
int[] RowSums(int[][] matrix)
{
int rows = matrix.Length;
int[] sums = new int[rows];
for (int i = 0; i < rows; i++)
{
int sum = 0;
for (int j = 0; j < matrix[i].Length; j++)
{
sum += matrix[i][j];
}
sums[i] = sum;
}
return sums;
}Multiply two matrices:
Each element result[i][j] is the sum of products of row i from the first matrix and column j from the second matrix:
result[i][j] += matrix1[i][k] * matrix2[k][j] for each k.
The first matrix must have as many columns as the second matrix has rows.
int[][] MultiplyMatrices(int[][] a, int[][] b)
{
int rows = a.Length;
int cols = b[0].Length;
int inner = b.Length;
int[][] result = new int[rows][];
for (int i = 0; i < rows; i++)
{
result[i] = new int[cols];
for (int j = 0; j < cols; j++)
{
for (int k = 0; k < inner; k++)
{
result[i][j] += a[i][k] * b[k][j];
}
}
}
return result;
}Try it yourself
public class MultiplyMatrices
{
// Implement the MultiplyMatrices method
public static int[][] multiplyMatrices(int[][] matrix1, int[][] matrix2)
{
// Write your code here
}
}This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Logic & Flow
1Multi-dimensional Arrays
2D Arrays BasicsDeclaring and Initializing 2DAccessing 2D Array ElementsNested Loops with 2D ArraysJagged ArraysCommon Matrix OperationsRecap - Multi-dimensional4Flow Control Techniques
Early ReturnsGuard ClausesJump Statements (goto)Break and ContinueFlatten Nested Conditionals7Logical Operators Advanced
Short-Circuit EvaluationConditional Logical OperatorsOperator PrecedenceRecap - Advanced Operators2Advanced Decision Making
Multiple ConditionsComplex Boolean LogicIf vs. Switch ComparisonNested Switch StatementsRecap - Advanced Decisions5Exception Handling
Try-Catch BasicsException TypesMultiple Catch BlocksWorking with FilesFinally BlockUsing vs. Try-FinallyCustom ExceptionsRecap - Error Handling3Loop Enhancements
Loop PerformanceIterating ComplexEach Loop TypeRefactoring LoopsRecap - Optimized Loops6Null Handling
Null Reference BasicsNullable Value TypesNull Checking PatternsDefensive ProgrammingRecap - Null Safety