C # basic matrix Math Library tutorial,

Source: Internet
Author: User

C # basic matrix Math Library tutorial,

First, start SimpleMatrix. cs and define the total number of rows, total number of columns, and all data (double type)

using System;using System.IO;namespace NeuralDefs.Matrix{    public class SimpleMatrix : IMatrix    {        public int Row { get; set; }        public int Column { get; set; }        public double[,] Data { get; set; }

The IMatrix matrix is used for organization, because I also wrote a sparse matrix. This interface can be written again when introducing the sparse matrix.

1. First, implement the basic functions of a simple matrix-assignment and Output

I often use csv files to store and view matrices in a natural way.

public SimpleMatrix(int row, int col)        {            // init matrix            Row = row;            Column = col;            Data = new double[row, col];            for (var i = 0; i < row; i++)            {                for (var j = 0; j < col; j++)                {                    Data[i, j] = 0;                }            }        }        public SimpleMatrix(string fileName)        {            //var splitUnit = '\t';            var splitUnit = ',';            // count columns            var srCol = new StreamReader(fileName);            var firstLine = srCol.ReadLine();            if (firstLine != null)            {                var firstArray = firstLine.Split(splitUnit);                Column = firstArray.Length;            }            srCol.Close();            // count rows            Row = 0;            var srRow = new StreamReader(fileName);            while (srRow.ReadLine() != null)            {                Row++;            }            srRow.Close();            // init matrix            Data = new double[Row, Column];            // fill matrix            var srData = new StreamReader(fileName);            var curRow = 0;            string line;            while ((line = srData.ReadLine()) != null)            {                var lineArray = line.Split(splitUnit);                for (var i = 0; i < lineArray.Length; i++)                {                    Data[curRow, i] = double.Parse(lineArray[i]);                }                curRow++;            }            srData.Close();        }        public void WriteTo(string path)        {            var fs = new FileStream(path, FileMode.Create);            var sw = new StreamWriter(fs);            for (var i = 0; i < Row; i++)            {                sw.WriteLine(this.RowVector(i).ToSingleLineRow());            }            sw.Close();            fs.Close();        }

2. Use the index tool to retrieve the subscript

public double this[int row, int column]        {            get { return Data[row, column]; }            set { Data[row, column] = value; }        }

3. randomization (used for Neural Network Initial Value assignment and other purposes)

public void Randomize()        {            var rm = new Random();            for (var i = 0; i < Row; i++)            {                for (var j = 0; j < Column; j++)                {                    Data[i, j] = rm.Next(-100, 100) / 1000.0;                }            }        }

4. Fetch a row

public SimpleMatrix RowVector(int row)        {            var result = new SimpleMatrix(1, Column);            for (var i = 0; i < Column; i++)            {                result[0, i] = Data[row, i];            }            return result;        }

5. Subtraction

public static SimpleMatrix operator -(SimpleMatrix a, SimpleMatrix b)        {            var minus = new SimpleMatrix(a.Row, a.Column);            for (var i = 0; i < minus.Row; i++)            {                for (var j = 0; j < minus.Column; j++)                {                    minus[i, j] = a[i, j] - b[i, j];                }            }            return minus;        }

6. Norm

public static double Norm2(SimpleMatrix a)        {            var norm = 0.0;            for (var i = 0; i < a.Row; i++)            {                for (var j = 0; j < a.Column; j++)                {                    norm += a[i, j] * a[i, j];                }            }            return Math.Sqrt(norm);        }

7. connect two vectors

public static SimpleMatrix Link(SimpleMatrix vector1, SimpleMatrix vector2)        {            // check is vector            if (vector1.Column != 1 || vector2.Column != 1)                return null;            var newRow = vector1.Row + vector2.Row;            var result = new SimpleMatrix(newRow, 1);            for (var i = 0; i < vector1.Row; i++)            {                result[i, 0] = vector1[i, 0];            }            for (var i = 0; i < vector2.Row; i++)            {                result[vector1.Row + i, 0] = vector2[i, 0];            }            return result;        }

8. Single Element Matrix

 public static SimpleMatrix SingleValueMatrix(double val)        {            return new SimpleMatrix(1, 1) { Data = { [0, 0] = val } };        }

9. Maximum absolute value

public static double MaxAbsMember(SimpleMatrix a)        {            var max = -1.0;            foreach (var d in a.Data)            {                if (Math.Abs(d) > max)                    max = Math.Abs(d);            }            return max;        }

10. Matrix transpose

public static SimpleMatrix Transpose(SimpleMatrix a)        {            var result = new SimpleMatrix(a.Column, a.Row);            for (var i = 0; i < result.Row; i++)            {                for (var j = 0; j < result.Column; j++)                {                    result[i, j] = a[j, i];                }            }            return result;        }

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

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.