Matrix.cs 3.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text;
  5. using System.Threading.Tasks;
  6. using System.Windows;
  7. namespace Matrix
  8. {
  9. class MyMatrix
  10. {
  11. public double[,] data; //
  12. public int Rows
  13. {
  14. get { return data.GetLength(0); }
  15. }
  16. public int Columns
  17. {
  18. get { return data.GetLength(1); }
  19. }
  20. public MyMatrix(double[,] data)
  21. {
  22. this.data = data;
  23. }
  24. public static MyMatrix operator +(MyMatrix matrix1, MyMatrix matrix2)
  25. {
  26. if (matrix1.Rows == matrix2.Rows && matrix1.Columns == matrix2.Columns)
  27. {
  28. double[,] array = new double[matrix1.Rows, matrix1.Columns];
  29. for (int i = 0; i < matrix1.Rows; i++)
  30. {
  31. for (int j = 0; j < matrix1.Columns; j++)
  32. {
  33. array[i, j] = matrix1.data[i, j] + matrix2.data[i, j];
  34. }
  35. }
  36. return new MyMatrix(array);
  37. }
  38. else
  39. {
  40. throw new Exception("Размер матриц должен совпадать");
  41. }
  42. }
  43. public static MyMatrix operator -(MyMatrix matrix1, MyMatrix matrix2)
  44. {
  45. if (matrix1.Rows == matrix2.Rows && matrix1.Columns == matrix2.Columns)
  46. {
  47. double[,] array = new double[matrix1.Rows, matrix1.Columns];
  48. for (int i = 0; i < matrix1.Rows; i++)
  49. {
  50. for (int j = 0; j < matrix1.Columns; j++)
  51. {
  52. array[i, j] = matrix1.data[i, j] - matrix2.data[i, j];
  53. }
  54. }
  55. return new MyMatrix(array);
  56. }
  57. else
  58. {
  59. throw new Exception("Размер матриц должен совпадать");
  60. }
  61. }
  62. public static MyMatrix operator *(MyMatrix matrix1, MyMatrix matrix2)
  63. {
  64. }
  65. public static MyMatrix operator *(MyMatrix matrix1, double num)
  66. {
  67. double[,] array = new double[matrix1.Rows, matrix1.Columns];
  68. for (int i = 0; i < matrix1.Rows; i++)
  69. {
  70. for (int j = 0; j < matrix1.Columns; j++)
  71. {
  72. array[i, j] = matrix1.data[i, j] * num;
  73. }
  74. }
  75. return new MyMatrix(array);
  76. }
  77. public static MyMatrix operator *(double num, MyMatrix matrix1)
  78. {
  79. return matrix1 * num;
  80. }
  81. public override string ToString()
  82. {
  83. StringBuilder sb = new StringBuilder("", Rows * Columns * 2);
  84. for (int i = 0; i < Rows; i++)
  85. {
  86. for (int j = 0; j < Columns; j++)
  87. {
  88. if (j + 1 != Columns)
  89. {
  90. sb.Append($"{data[i, j]}, ");
  91. }
  92. else
  93. {
  94. sb.Append($"{data[i, j]}");
  95. }
  96. }
  97. sb.Append("\n");
  98. }
  99. return sb.ToString();
  100. }
  101. }
  102. }