Ejemplo n.º 1
0
        /// <summary>
        /// Parses multiline text input  from a textreader into a Matrix where each line
        /// corresponsd to a row and the items on the line are space deliminted
        /// </summary>
        /// <param name="reader">The TextReader</param>
        /// <returns>The Matrix</returns>
        public static Matrix3d Load(this Matrix3d mat, TextReader reader)
        {
            List <double[]> rows = new List <double[]>();
            Regex           rx   = new Regex(@"\s+");

            while (reader.Peek() != -1)
            {
                string line = reader.ReadLine().Trim();

                if (line != "")
                {
                    string[] rowStrs   = rx.Split(line);
                    double[] matrixRow = new double[rowStrs.Length];
                    for (int i = 0; i < rowStrs.Length; i++)
                    {
                        double val = 0;
                        if (double.TryParse(rowStrs[i], out val))
                        {
                            matrixRow[i] = val;
                        }
                        else
                        {
                            throw new ArgumentException("Invalid string");
                        }
                    }
                    rows.Add(matrixRow);
                }
            }

            if (rows.Count > 1)
            {
                //Check that all rows have the same length
                int rowSize = rows[0].Length;
                for (int i = 1; i < rows.Count; i++)
                {
                    if (rows[i].Length != rowSize)
                    {
                        throw new ArgumentException("Rows of inconsistant length");
                    }
                }

                mat = mat.FromRowsList(rows);
                return(mat);
            }
            else if (rows.Count == 1)
            {
                mat = mat.FromRowsList(rows);
                return(mat);
            }
            else
            {
                return(mat);
            }
        }