C++/CLIでやったことをC#で2
行列クラスも書いた。
ただし、逆行列はまだ。
using System; namespace MyMath { /// <summary> /// 行列クラスです。 /// </summary> public class Matrix { private Fraction[,] m_elements; // コンストラクタ public Matrix( int row, int column ) { this.m_elements = new Fraction[row, column]; } public Matrix( Fraction[,] array ) { this.m_elements = array; } ~Matrix() { } // インデクサ public Fraction this[int i, int j] { set{ this.m_elements[i, j] = value; } get{ return this.m_elements[i, j]; } } // 行数を返す public int GetRow() { return m_elements.GetLength(0); } // 列数を返す public int GetColumn() { return m_elements.GetLength(1); } // 要素表示 public void Disp() { for( int i = 0; i < this.GetRow(); ++i ) { for( int j = 0; j < this.GetColumn(); ++j ) { Console.Write( "{0,6}", this[i, j] ); } Console.WriteLine(); } } // 演算子 public static Matrix operator+( Matrix a, Matrix b ) { int row = a.GetRow(); int column = a.GetColumn(); if( a.GetRow() < b.GetRow() ) row = b.GetRow(); if( a.GetColumn() < b.GetColumn() ) column = b.GetColumn(); Fraction[,] array = new Fraction[row,column]; for( int i = 0; i < row; ++i ) for( int j = 0; j < column; ++j ) array[i, j] = a[i, j] + b[i, j]; return new Matrix( array ); } public static Matrix operator-( Matrix a, Matrix b ) { int row = a.GetRow(); int column = a.GetColumn(); if( a.GetRow() < b.GetRow() ) row = b.GetRow(); if( a.GetColumn() < b.GetColumn() ) column = b.GetColumn(); Fraction[,] array = new Fraction[row,column]; for( int i = 0; i < row; ++i ) for( int j = 0; j < column; ++j ) array[i, j] = a[i, j] - b[i, j]; return new Matrix( array ); } public static Matrix operator *( Matrix a, Matrix b ) { int row = a.GetRow(); int column = a.GetColumn(); if( a.GetRow() < b.GetRow() ) row = b.GetRow(); if( a.GetColumn() < b.GetColumn() ) column = b.GetColumn(); Fraction[,] array = new Fraction[row,column]; for( int i = 0; i < row; ++i ) for( int j = 0; j < column; ++j ) { Fraction zero = new Fraction( 0, 1 ); array[i, j] = zero; for( int k = 0; k < column; ++k ) array[i, j] += a[i, k] * b[k, j]; } return new Matrix( array ); } } }