摘要
介紹矩陣的編程表示,矩陣的初等變換,化階梯矩陣及求方陣的行列式。
矩陣介紹
矩陣就是一個M×N平面的表格,用一個兩維數組就可以表示,為了輸入方便,我們用一個特殊格式的字 符串對矩陣進行初始化,用"|"分割每一行,用","分割每一列,並增加一個Show的方法列印出矩陣,為了 測試及調試的需要,還重寫了ToString()方法。
代碼
public class Matrix {
public int M { get; private set; }
public int N { get; private set; }
private readonly double[,] num = null;
#region 建構函式/Show
public Matrix(int m, int n, string input) {
M = m;
N = n;
num = new double[m, n];
if (!string.IsNullOrEmpty(input))
parseInput(input);
}
private void parseInput(string input) {
string[] rows = input.Split(new[] { '|' });
if (rows.Length != M)
throw new ArgumentException("row count err");
for (int i = 0; i < M; i++) {
string row = rows[i];
string[] cells = row.Split(new[] { ',' });
if (cells.Length != N)
throw new ArgumentException(string.Format("cells counte err:{0}", row));
for (int j = 0; j < N; j++) {
int cellValue;
if (!int.TryParse(cells[j], out cellValue))
throw new ArgumentException(string.Format("cell error:{0}", cells[j]));
num[i, j] = cellValue;
}
}
}
public void Show() {
for (int i = 0; i < M; i++) {
for (int j = 0; j < N; j++)
Console.Write("{0}\t", num[i, j]);
Console.WriteLine();
}
}
public override string ToString() {
StringBuilder sb = new StringBuilder();
for (int i = 0; i < M; i++) {
for (int j = 0; j < N; j++) {
sb.Append(num[i, j]);
if (j != N - 1)
sb.Append(',');
}
if (i != M - 1)
sb.Append('|');
}
return sb.ToString();
}
}