Matrix.cs 3.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116
  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, double num)
  63. {
  64. double[,] array = new double[matrix1.Rows, matrix1.Columns];
  65. for (int i = 0; i < matrix1.Rows; i++)
  66. {
  67. for (int j = 0; j < matrix1.Columns; j++)
  68. {
  69. array[i, j] = matrix1.data[i, j] * num;
  70. }
  71. }
  72. return new MyMatrix(array);
  73. }
  74. public static MyMatrix operator *(double num, MyMatrix matrix1)
  75. {
  76. return matrix1 * num;
  77. }
  78. public override string ToString()
  79. {
  80. StringBuilder sb = new StringBuilder("", Rows * Columns * 2);
  81. for (int i = 0; i < Rows; i++)
  82. {
  83. for (int j = 0; j < Columns; j++)
  84. {
  85. if (j + 1 != Columns)
  86. {
  87. sb.Append($"{data[i, j]}, ");
  88. }
  89. else
  90. {
  91. sb.Append($"{data[i, j]}");
  92. }
  93. }
  94. sb.Append("\n");
  95. }
  96. return sb.ToString();
  97. }
  98. }
  99. }