Advertisement
mrAnderson33

класс матрица

Apr 4th, 2017
266
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 7.42 KB | None | 0 0
  1. /* тз:
  2.  Реализовать класс квадратной матрицы произвольного размера и для него
  3. операции сложения, умножения, деления, нахождение определителя и транспонирования. При
  4. невозможности выполнить какую-либо операцию генерируйте исключение (Объект
  5. исключение должен быть объектом пользовательского класса, пронаследованного от
  6. Exception). Реализовать интерфейс ICloneable. Добавить возможность работы с элементами
  7. матрицы в цикле foreach. Примечание. Класс должен содержать не менее 3 различных
  8. конструкторов.
  9. */
  10.  
  11. using System;
  12. using System.Collections;
  13. using System.Collections.Generic;
  14. using System.Linq;
  15. using System.Text;
  16.  
  17. namespace lab5_a_
  18. {
  19.     class SquareMatrix : ICloneable, IEnumerable
  20.     {
  21.         private double [,]  arr {  set;  get;}
  22.  
  23.         public uint Size {
  24.             get
  25.             {
  26.                 return (uint) arr.GetLength(1);
  27.             }
  28.         }
  29.         public SquareMatrix(int size  = 0)
  30.         {
  31.             arr = new double[size,size];
  32.             arr.Initialize();
  33.         }
  34.         public SquareMatrix(SquareMatrix ob)
  35.         {
  36.             arr = (double[,])ob.arr.Clone();
  37.         }
  38.         public SquareMatrix(string[] str)
  39.         {
  40.             int len = str.Length;
  41.             arr = new double[len,len];
  42.        
  43.             int i = 0;
  44.             foreach(var buf in str)
  45.             {
  46.                 int j = 0;
  47.                 var temp = buf.Split(' ');
  48.                 foreach (var s in temp) double.TryParse(s, out arr[i, j++]);
  49.                 i++;
  50.             }
  51.         }
  52.         public SquareMatrix(double [,] arr)
  53.         {
  54.             this.arr = (double[,])arr.Clone();
  55.         }
  56.         public void Print()
  57.         {
  58.             for (int i = 0; i < arr.GetLength(1); ++i)
  59.             {
  60.                 for (int j = 0; j < arr.GetLength(1); ++j)
  61.                     Console.Write(string.Format("{0} ", arr[i, j]));
  62.                 Console.Write("\n");
  63.             }
  64.            
  65.         }
  66.         public void SetValue()
  67.         {
  68.             string buf ;
  69.             var i = 0;
  70.             Console.WriteLine(@"введите матрицу матрицу размером {0}x{0}(:wq для выхода)
  71.                (цифры вводятся через пробел):", Size);
  72.             while ( (buf = Console.ReadLine() )!= ":wq")
  73.             {
  74.      
  75.                     int j = 0;
  76.                     var temp = buf.Split(' ');
  77.                     try
  78.                     {
  79.                         foreach (var s in temp) double.TryParse(s, out arr[i, j++]);
  80.                     }
  81.                     catch (System.IndexOutOfRangeException) { throw new MyExeption("Ошибка! вы ввели не тот символ или написали слишком много значений, попробуйте ввести строку снова"); }
  82.                     i++;
  83.                
  84.                
  85.                
  86.             }
  87.  
  88.         }
  89.         public void SetAt(uint row, uint column, double num)
  90.         {
  91.             arr[row, column] = num;
  92.         }
  93.  
  94.         public IEnumerator<double>  GetEnumerator()
  95.         {
  96.             foreach (var n in arr) yield return n;
  97.         }
  98.         IEnumerator IEnumerable.GetEnumerator()
  99.         {
  100.             return GetEnumerator();
  101.         }
  102.  
  103.         public SquareMatrix GetMinor(int row, int column)
  104.         {
  105.             var temp = new double[Size - 1, Size - 1];
  106.             for (int i = 0; i <Size; i++)
  107.                 for (int j = 0; j < Size; j++)
  108.                 {
  109.                     if ((i != row) || (j != column))
  110.                     {
  111.                         if (i > row && j < column) temp[i - 1, j] = arr[i, j];
  112.                         if (i < row && j > column) temp[i, j - 1] = arr[i, j];
  113.                         if (i > row && j > column) temp[i - 1, j - 1] = arr[i, j];
  114.                         if (i < row && j < column) temp[i, j] = arr[i, j];
  115.                     }
  116.                 }
  117.             return new SquareMatrix(temp);
  118.         }
  119.  
  120.         public double Determinant()
  121.         {
  122.             if (Size == 1) return arr[0, 0];
  123.             else if (Size == 2)
  124.             {
  125.                 return arr[0, 0] * arr[1, 1] - arr[0, 1] * arr[1, 0];
  126.             }
  127.             else
  128.             {
  129.                 double det = 0;
  130.                 for (int j = 0; j <Size; j++)
  131.                 {
  132.                     det += Math.Pow(-1, 0 + j) * arr[0, j] * this.GetMinor(0, j).Determinant();
  133.                 }
  134.                 return det;
  135.             }
  136.         }
  137.  
  138.         public void Transp()
  139.         {
  140.  
  141.             for (int i = 0; i < Size; i++)
  142.             {
  143.                 for (int j = 0; j < i; j++)
  144.                 {
  145.                     var tmp = arr[i, j];
  146.                     arr[i, j] = arr[j, i];
  147.                     arr[j, i] = tmp;
  148.                 }
  149.             }
  150.         }
  151.  
  152.         public object Clone()
  153.         {
  154.  
  155.             var newMatrix = (double[,])arr.Clone();
  156.             return new SquareMatrix(newMatrix);
  157.         }
  158.  
  159.         public static SquareMatrix operator+(SquareMatrix left, SquareMatrix right)
  160.         {
  161.             var temp = new double[left.Size,left.Size];
  162.  
  163.             for (int i = 0; i < temp.GetLength(1); ++i)
  164.                 for (int j = 0; j < temp.GetLength(1); ++j)
  165.                     temp[i, j] = left.arr[i, j] + right.arr[i, j];
  166.  
  167.             return new SquareMatrix(temp);
  168.         }
  169.  
  170.         public static SquareMatrix operator *(SquareMatrix left, SquareMatrix right)
  171.         {
  172.             var len = left.Size;
  173.             var temp = new double[len,len];
  174.  
  175.             for (int i = 0; i < len; i++)
  176.             {
  177.                 for (int j = 0; j < len; j++)
  178.                 {
  179.                     for (int k = 0; k < len; k++)
  180.                     {
  181.                         temp[i, j] += left.arr[i, k] * right.arr[k, j];
  182.                     }
  183.                 }
  184.             }
  185.  
  186.             return new SquareMatrix(temp);
  187.         }
  188.  
  189.         public static SquareMatrix operator/(SquareMatrix left, SquareMatrix right)
  190.         {
  191.             return left * right.Inverse();
  192.         }
  193.        
  194.         public  SquareMatrix Inverse()
  195.         {
  196.            
  197.             if (this.Determinant() == 0) throw new MyExeption("Невозможно найти обратную марицу");
  198.             int len =(int) Size;
  199.             var temp = new double[len, len];
  200.             var del = 1 / this.Determinant();
  201.             for(int i = 0; i < len; ++ i)
  202.                 for(int j =0; j <len; ++j)
  203.                    //try
  204.                     {
  205.                         temp[i, j] = this.GetMinor(i, j).Determinant() * del;
  206.                         temp[i, j] *= ((i + j) % 2 == 0) ? 1 : -1;
  207.                     }
  208.                    /*catch (System.IndexOutOfRangeException ex)
  209.                     {
  210.                         Console.WriteLine(ex.Message);
  211.                    }*/
  212.             var m = new SquareMatrix(temp);
  213.             m.Transp();
  214.  
  215.             return m;
  216.                
  217.  
  218.         }
  219.  
  220.     }
  221.    
  222.  
  223.    
  224. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement