Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- namespace _06.MatrixClass
- {
- class NotSameSizeException : System.Exception
- {
- public NotSameSizeException(string message)
- : base(message)
- {
- }
- }
- class Matrix
- {
- private int[,] matrix;
- public int row, col;
- public Matrix(int[,] matrix)
- {
- this.matrix = matrix;
- this.row = matrix.GetLength(0);
- this.col = matrix.GetLength(1);
- }
- public Matrix(int row, int col)
- {
- this.row = row;
- this.col = col;
- this.matrix = new int[row, col];
- }
- public int this[int x, int y]
- {
- get { return this.matrix[x, y]; }
- set { matrix[x, y] = value; }
- }
- public static Matrix operator +(Matrix m1, Matrix m2)
- {
- Matrix m3 = new Matrix(m1.row, m1.col);
- if (m1.col != m2.col && m1.row != m2.row)
- {
- throw new NotSameSizeException("Matrices must be with same dimesions");
- }
- else
- {
- for (int i = 0; i < m1.row; i++)
- {
- for (int j = 0; j < m1.col; j++)
- {
- m3[i, j] = m1[i, j] + m2[i, j];
- }
- }
- }
- return m3;
- }
- public static Matrix operator -(Matrix m1, Matrix m2)
- {
- Matrix m3 = new Matrix(m1.row, m1.col);
- if (m1.row != m2.row || m1.col != m2.col)
- {
- throw new NotSameSizeException("Matrices must be with same dimesions");
- }
- else
- {
- for (int i = 0; i < m1.row; i++)
- {
- for (int j = 0; j < m1.col; j++)
- {
- m3[i, j] = m1[i, j] - m2[i, j];
- }
- }
- }
- return m3;
- }
- public static Matrix operator *(Matrix m1, Matrix m2)
- {
- if (m1.col != m2.row)
- {
- throw new NotSameSizeException("You cannot multiply " + m1.row + "x" + m1.col + " and " + m2.row + "x" + m2.col + " matrices");
- }
- Matrix m3 = new Matrix(m1.row, m2.col);
- for (int i = 0; i < m1.row; i++)
- {
- for (int j = 0; j < m2.col; j++)
- {
- int currentResult = 0;
- for (int m = 0; m < m2.row; m++)
- {
- currentResult += m2[m, j] * m1[i, m];
- }
- m3[i, j] = currentResult;
- }
- }
- return m3;
- }
- public override string ToString()
- {
- StringBuilder sb = new StringBuilder();
- for (int i = 0; i < this.row; i++)
- {
- for (int j = 0; j < col; j++)
- {
- sb.Append(this.matrix[i, j] + " ");
- }
- sb.AppendLine();
- }
- return sb.ToString();
- }
- }
- class Test
- {
- public static void Main()
- {
- int[,] mx1 = {
- {0,1,3},
- {3,4,5}
- };
- int[,] mx2 = {
- {1,2},
- {3,4},
- {5,6}
- };
- int[,] mx3 = new int[mx1.GetLength(0), mx2.GetLength(1)];
- Matrix m1 = new Matrix(mx1);
- Matrix m2 = new Matrix(mx2);
- Matrix m3 = m1 * m2;
- Console.WriteLine(m3);
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement