矩阵算法入门2011-09-30 博客园 蛙蛙王子摘要介绍矩阵的编程表示,矩阵的初等变换,化阶梯矩阵及求方阵的行列式。矩阵介绍矩阵就是一个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} ", 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(); } }