矩陣演算法入門

來源:互聯網
上載者:User

摘要

介紹矩陣的編程表示,矩陣的初等變換,化階梯矩陣及求方陣的行列式。

矩陣介紹

矩陣就是一個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();
     }
}

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.