Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- static class MatrixMath
- {
- public static void PrintMatrix(int[,] matrix)
- {
- int n = matrix.GetLength(0);
- int m = matrix.GetLength(1);
- for (int i = 0; i < n; i++)
- {
- for (int j = 0; j < m; j++)
- {
- Console.Write($"{matrix[i, j]} ");
- }
- Console.WriteLine();
- }
- }
- public static void RandomElements(int[,] matrix)
- {
- Random rand = new Random();
- int n = matrix.GetLength(0);
- int m = matrix.GetLength(1);
- for (int i = 0; i < n; i++)
- {
- for (int j = 0; j < m; j++)
- {
- matrix[i, j] = rand.Next(10);
- }
- }
- }
- public static void ChangeRows(int[,] matrix, int row1, int row2)
- {
- int n = matrix.GetLength(0);
- int m = matrix.GetLength(1);
- if (row1 < 0 || row2 < 0 || row1 >= n || row2 >= n)
- {
- throw new ArgumentException("Rows problem");
- }
- for (int i = 0; i < m; i++)
- {
- // matrix[row1, i] <=> matrix[row2, i]
- int temp = matrix[row1, i];
- matrix[row1, i] = matrix[row2, i];
- matrix[row2, i] = temp;
- }
- }
- public static int[,] ScalarMult(int[,] matrix, int num)
- {
- int n = matrix.GetLength(0);
- int m = matrix.GetLength(1);
- int[,] result = new int[n, m];
- for (int i = 0; i < n; i++)
- {
- for (int j = 0; j < m; j++)
- {
- result[i, j] = matrix[i, j] * num;
- }
- }
- return result;
- }
- public static int[,] AddMatrix(int[,] matrix1, int[,] matrix2)
- {
- int n1 = matrix1.GetLength(0);
- int m1 = matrix1.GetLength(1);
- int n2 = matrix1.GetLength(0);
- int m2 = matrix1.GetLength(1);
- if (n1 != n2 || m1 != m2)
- {
- throw new ArgumentException("Matrix dimensions problem!");
- }
- int[,] result = new int[n1, m1];
- for (int i = 0; i < n1; i++)
- {
- for (int j = 0; j < m1; j++)
- {
- result[i, j] = matrix1[i, j] + matrix2[i, j];
- }
- }
- return result;
- }
- public static int[,] Identity(int n)
- {
- int[,] result = new int[n, n];
- for (int i = 0; i < n; i++)
- {
- result[i, i] = 1;
- }
- return result;
- }
- public static int[,] Scalar(int size, int num)
- {
- return ScalarMult(Identity(size), num);
- }
- public static int[,] Transponate(int[,] matrix)
- {
- int n = matrix.GetLength(0);
- int m = matrix.GetLength(1);
- int[,] result = new int[m, n];
- // to do
- return result;
- }
- public static int[,] Multiply(int[,] matrix1, int[,] matrix2)
- {
- int m1 = matrix1.GetLength(0);
- int n1 = matrix1.GetLength(1);
- int m2 = matrix2.GetLength(0);
- int n2 = matrix2.GetLength(1);
- if (n1 != m2) throw new Exception("M, N error");
- int[,] mult = new int[m1, n2];
- int m = m1;
- int n = n2;
- for (int row = 0; row < m; row++)
- {
- for (int col = 0; col < n; col++)
- {
- for (int k = 0; k < m; k++)
- {
- mult[row, col] += matrix1[row, k] * matrix2[k, col];
- }
- }
- }
- // to do
- return mult;
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement