using System; using CenterSpace.NMath.Core; namespace CenterSpace.NMath.Examples.CSharp { /// <summary> /// A .NET example in C# showing how to use the indexing class Range with the matrix classes. /// </summary> public class MatrixRangeExample { static void Main( string[] args ) { int rows = 5, cols = 5; var A = new DoubleMatrix( rows, cols, 0, 1 ); // | 0 5 10 15 20 | // | 1 6 11 16 21 | // A = | 2 7 12 17 22 | // | 3 8 13 18 23 | // | 4 9 14 19 24 | Console.WriteLine(); Console.WriteLine( "A..." ); Console.WriteLine( A.ToTabDelimited() ); Console.WriteLine(); // Last two columns of the matrix A: var colRange = new Range( 3, 4 ); var rowRange = Range.All; DoubleMatrix ALast2Col = A[rowRange, colRange]; // | 15 20 | // | 16 21 | // ALast2Col = | 17 22 | // | 18 23 | // | 19 24 | Console.WriteLine( "ALast2Col..." ); Console.WriteLine( ALast2Col.ToTabDelimited() ); Console.WriteLine(); // Could also get this by specifying all elements from the 4th column // to the end using the End value from the enum // CenterSpace.NMathFunctions.Core.Position ALast2Col = A[rowRange, new Range( 3, Position.End )]; Console.WriteLine( "ALast2Col..." ); Console.WriteLine( ALast2Col.ToTabDelimited() ); Console.WriteLine(); // You can use negative strides too. Here is the matrix A, reversed. // We re-use the Range objects, setting their start, stop, and stride // fields using the Set method. rowRange = new Range( rows - 1, 0, -1 ); colRange.Set( cols - 1, 0, -1 ); DoubleMatrix ARev = A[rowRange, colRange]; // | 24 19 14 9 4 | // | 23 18 13 8 3 | // ARev = | 22 17 12 7 2 | // | 21 16 11 6 1 | // | 20 15 10 5 0 | Console.WriteLine( "ARev..." ); Console.WriteLine( ARev.ToTabDelimited() ); Console.WriteLine(); // Notice that when you create a new DoubleMatrix using the Range or Slice class, // you are creating a different "view" of the Matrix data. That is, the // DoubleMatrix instance returned by the indexing operator taking a Range object, // and the DoubleMatrix instance being indexed share the same data: ARev[0, 0] = 100; Console.WriteLine( "ARev[0,0] = {0}", ARev[0, 0] ); // uRev = [0 8 7 6 5 4 3 2 1 0] Console.WriteLine(); Console.WriteLine( "A[{0},{1}] = {2}", rows - 1, cols - 1, A[rows - 1, cols - 1] ); // A[4,4] Console.WriteLine(); // We now use the DoubleMatrix method Set(Range,Range,value) to change the // contents of A to alternate values 0 and 1 - like a checker board. var evenElts = new Range( 0, Position.End, 2 ); var oddElts = new Range( 1, Position.End, 2 ); A.Set( evenElts, oddElts, 0 ); A.Set( evenElts, evenElts, 1 ); A.Set( oddElts, evenElts, 0 ); A.Set( oddElts, oddElts, 1 ); // | 1 0 1 0 1 | // | 0 1 0 1 0 | // A = | 1 0 1 0 1 | // | 0 1 0 1 0 | // | 1 0 1 0 1 | Console.WriteLine( "A..." ); Console.WriteLine( A.ToTabDelimited() ); Console.WriteLine(); Console.WriteLine( "Press Enter Key" ); Console.Read(); } // Main }// class }// namespace← All NMath Code Examples