Browse Source

examples: Added Andriy's first set of examples

bug: added Andriy insertrow fix
la-knuth
Marcus Cuda 16 years ago
parent
commit
24858f7833
  1. 28
      src/Examples/Examples.csproj
  2. 144
      src/Examples/LinearAlgebra/DirectSolvers.cs
  3. 105
      src/Examples/LinearAlgebra/Factorization/Cholesky.cs
  4. 188
      src/Examples/LinearAlgebra/Factorization/Evd.cs
  5. 135
      src/Examples/LinearAlgebra/Factorization/LU.cs
  6. 132
      src/Examples/LinearAlgebra/Factorization/QR.cs
  7. 186
      src/Examples/LinearAlgebra/Factorization/Svd.cs
  8. 246
      src/Examples/LinearAlgebra/MatrixArithmeticOperations.cs
  9. 208
      src/Examples/LinearAlgebra/MatrixDataAccessor.cs
  10. 112
      src/Examples/LinearAlgebra/MatrixInitialization.cs
  11. 129
      src/Examples/LinearAlgebra/MatrixNorms.cs
  12. 173
      src/Examples/LinearAlgebra/MatrixRowColumnOperations.cs
  13. 112
      src/Examples/LinearAlgebra/MatrixSpecialNumbers.cs
  14. 120
      src/Examples/LinearAlgebra/MatrixTransposeAndInverse.cs
  15. 123
      src/Examples/LinearAlgebra/MatrixTriangular.cs
  16. 209
      src/Examples/LinearAlgebra/VectorArithmeticOperations.cs
  17. 158
      src/Examples/LinearAlgebra/VectorDataAccessor.cs
  18. 98
      src/Examples/LinearAlgebra/VectorInitialization.cs
  19. 2
      src/Numerics/LinearAlgebra/Generic/Matrix.cs

28
src/Examples/Examples.csproj

@ -10,7 +10,7 @@
<AppDesignerFolder>Properties</AppDesignerFolder>
<RootNamespace>Examples</RootNamespace>
<AssemblyName>Examples</AssemblyName>
<TargetFrameworkVersion>v3.5</TargetFrameworkVersion>
<TargetFrameworkVersion>v4.0</TargetFrameworkVersion>
<FileAlignment>512</FileAlignment>
<FileUpgradeFlags>
</FileUpgradeFlags>
@ -31,6 +31,7 @@
<IsWebBootstrapper>false</IsWebBootstrapper>
<UseApplicationTrust>false</UseApplicationTrust>
<BootstrapperEnabled>true</BootstrapperEnabled>
<TargetFrameworkProfile />
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
<DebugSymbols>true</DebugSymbols>
@ -56,6 +57,7 @@
<Reference Include="System.Core">
<RequiredTargetFramework>3.5</RequiredTargetFramework>
</Reference>
<Reference Include="System.Numerics" />
<Reference Include="System.Xml.Linq">
<RequiredTargetFramework>3.5</RequiredTargetFramework>
</Reference>
@ -66,6 +68,24 @@
<Reference Include="System.Xml" />
</ItemGroup>
<ItemGroup>
<Compile Include="IExample.cs" />
<Compile Include="LinearAlgebra\DirectSolvers.cs" />
<Compile Include="LinearAlgebra\Factorization\Cholesky.cs" />
<Compile Include="LinearAlgebra\Factorization\Evd.cs" />
<Compile Include="LinearAlgebra\Factorization\LU.cs" />
<Compile Include="LinearAlgebra\MatrixNorms.cs" />
<Compile Include="LinearAlgebra\Factorization\QR.cs" />
<Compile Include="LinearAlgebra\Factorization\Svd.cs" />
<Compile Include="LinearAlgebra\MatrixArithmeticOperations.cs" />
<Compile Include="LinearAlgebra\MatrixDataAccessor.cs" />
<Compile Include="LinearAlgebra\MatrixInitialization.cs" />
<Compile Include="LinearAlgebra\MatrixRowColumnOperations.cs" />
<Compile Include="LinearAlgebra\MatrixSpecialNumbers.cs" />
<Compile Include="LinearAlgebra\MatrixTransposeAndInverse.cs" />
<Compile Include="LinearAlgebra\MatrixTriangular.cs" />
<Compile Include="LinearAlgebra\VectorArithmeticOperations.cs" />
<Compile Include="LinearAlgebra\VectorDataAccessor.cs" />
<Compile Include="LinearAlgebra\VectorInitialization.cs" />
<Compile Include="Properties\AssemblyInfo.cs" />
</ItemGroup>
<ItemGroup>
@ -85,6 +105,12 @@
<Install>true</Install>
</BootstrapperPackage>
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\Numerics\Numerics.csproj">
<Project>{B7CAE5F4-A23F-4438-B5BE-41226618B695}</Project>
<Name>Numerics</Name>
</ProjectReference>
</ItemGroup>
<Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
<!-- To modify your build process, add your task inside one of the targets below and uncomment it.
Other similar extension points exist, see Microsoft.Common.targets.

144
src/Examples/LinearAlgebra/DirectSolvers.cs

@ -0,0 +1,144 @@
// <copyright file="DirectSolvers.cs" company="Math.NET">
// Math.NET Numerics, part of the Math.NET Project
// http://numerics.mathdotnet.com
// http://github.com/mathnet/mathnet-numerics
// http://mathnetnumerics.codeplex.com
// Copyright (c) 2009-2010 Math.NET
// Permission is hereby granted, free of charge, to any person
// obtaining a copy of this software and associated documentation
// files (the "Software"), to deal in the Software without
// restriction, including without limitation the rights to use,
// copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following
// conditions:
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
// OTHER DEALINGS IN THE SOFTWARE.
// </copyright>
namespace Examples.LinearAlgebra
{
using System;
using System.Globalization;
using MathNet.Numerics.LinearAlgebra.Double;
using MathNet.Numerics.LinearAlgebra.Generic.Factorization;
/// <summary>
/// Direct solvers (using matrix decompositions)
/// </summary>
/// <seealso cref="http://en.wikipedia.org/wiki/Numerical_analysis#Direct_and_iterative_methods"/>
public class DirectSolvers : IExample
{
/// <summary>
/// Gets the name of this example
/// </summary>
public string Name
{
get
{
return "Direct solvers";
}
}
/// <summary>
/// Gets the description of this example
/// </summary>
public string Description
{
get
{
return "Solve linear equations using matrix decompositions";
}
}
/// <summary>
/// Run example
/// </summary>
public void Run()
{
// Format matrix output to console
var formatProvider = (CultureInfo)CultureInfo.InvariantCulture.Clone();
formatProvider.TextInfo.ListSeparator = " ";
// Solve next system of linear equations (Ax=b):
// 5*x + 2*y - 4*z = -7
// 3*x - 7*y + 6*z = 38
// 4*x + 1*y + 5*z = 43
// Create matrix "A" with coefficients
var matrixA = new DenseMatrix(new[,] { { 5.00, 2.00, -4.00 }, { 3.00, -7.00, 6.00 }, { 4.00, 1.00, 5.00 } });
Console.WriteLine(@"Matrix 'A' with coefficients");
Console.WriteLine(matrixA.ToString("#0.00\t", formatProvider));
Console.WriteLine();
// Create vector "b" with the constant terms.
var vectorB = new DenseVector(new[] { -7.0, 38.0, 43.0 });
Console.WriteLine(@"Vector 'b' with the constant terms");
Console.WriteLine(vectorB.ToString("#0.00\t", formatProvider));
Console.WriteLine();
// 1. Solve linear equations using LU decomposition
var resultX = matrixA.LU().Solve(vectorB);
Console.WriteLine(@"1. Solution using LU decomposition");
Console.WriteLine(resultX.ToString("#0.00\t", formatProvider));
Console.WriteLine();
// 2. Solve linear equations using QR decomposition
resultX = matrixA.QR().Solve(vectorB);
Console.WriteLine(@"2. Solution using QR decomposition");
Console.WriteLine(resultX.ToString("#0.00\t", formatProvider));
Console.WriteLine();
// 3. Solve linear equations using SVD decomposition
matrixA.Svd(true).Solve(vectorB, resultX);
Console.WriteLine(@"3. Solution using SVD decomposition");
Console.WriteLine(resultX.ToString("#0.00\t", formatProvider));
Console.WriteLine();
// 4. Solve linear equations using Gram-Shmidt decomposition
matrixA.GramSchmidt().Solve(vectorB, resultX);
Console.WriteLine(@"4. Solution using Gram-Shmidt decomposition");
Console.WriteLine(resultX.ToString("#0.00\t", formatProvider));
Console.WriteLine();
// 5. Verify result. Multiply coefficient matrix "A" by result vector "x"
var reconstructVecorB = matrixA * resultX;
Console.WriteLine(@"5. Multiply coefficient matrix 'A' by result vector 'x'");
Console.WriteLine(reconstructVecorB.ToString("#0.00\t", formatProvider));
Console.WriteLine();
// To use Cholesky or Eigenvalue decomposition coefficient matrix must be
// symmetric (for Evd and Cholesky) and positive definite (for Cholesky)
// Multipy matrix "A" by its transpose - the result will be symmetric and positive definite matrix
var newMatrixA = matrixA.TransposeAndMultiply(matrixA);
Console.WriteLine(@"Symmetric positive definite matrix");
Console.WriteLine(newMatrixA.ToString("#0.00\t", formatProvider));
Console.WriteLine();
// 6. Solve linear equations using Cholesky decomposition
newMatrixA.Cholesky().Solve(vectorB, resultX);
Console.WriteLine(@"6. Solution using Cholesky decomposition");
Console.WriteLine(resultX.ToString("#0.00\t", formatProvider));
Console.WriteLine();
// 7. Solve linear equations using eigen value decomposition
newMatrixA.Evd().Solve(vectorB, resultX);
Console.WriteLine(@"7. Solution using eigen value decomposition");
Console.WriteLine(resultX.ToString("#0.00\t", formatProvider));
Console.WriteLine();
// 8. Verify result. Multiply new coefficient matrix "A" by result vector "x"
reconstructVecorB = newMatrixA * resultX;
Console.WriteLine(@"8. Multiply new coefficient matrix 'A' by result vector 'x'");
Console.WriteLine(reconstructVecorB.ToString("#0.00\t", formatProvider));
Console.WriteLine();
}
}
}

105
src/Examples/LinearAlgebra/Factorization/Cholesky.cs

@ -0,0 +1,105 @@
// <copyright file="Cholesky.cs" company="Math.NET">
// Math.NET Numerics, part of the Math.NET Project
// http://numerics.mathdotnet.com
// http://github.com/mathnet/mathnet-numerics
// http://mathnetnumerics.codeplex.com
// Copyright (c) 2009-2010 Math.NET
// Permission is hereby granted, free of charge, to any person
// obtaining a copy of this software and associated documentation
// files (the "Software"), to deal in the Software without
// restriction, including without limitation the rights to use,
// copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following
// conditions:
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
// OTHER DEALINGS IN THE SOFTWARE.
// </copyright>
namespace Examples.LinearAlgebra.Factorization
{
using System;
using System.Globalization;
using MathNet.Numerics.LinearAlgebra.Double;
using MathNet.Numerics.LinearAlgebra.Generic.Factorization;
/// <summary>
/// Cholesky factorization example. For a symmetric, positive definite matrix A, the Cholesky factorization
/// is an lower triangular matrix L so that A = L*L'
/// </summary>
/// <seealso cref="http://reference.wolfram.com/mathematica/ref/CholeskyDecomposition.html"/>
public class Cholesky : IExample
{
/// <summary>
/// Gets the name of this example
/// </summary>
public string Name
{
get
{
return "Cholesky factorization";
}
}
/// <summary>
/// Gets the description of this example
/// </summary>
public string Description
{
get
{
return "Perform the Cholesky factorization to the appropriate class";
}
}
/// <summary>
/// Run example
/// </summary>
/// <seealso cref="http://en.wikipedia.org/wiki/Cholesky_decomposition">Cholesky decomposition</seealso>
public void Run()
{
// Format matrix output to console
var formatProvider = (CultureInfo)CultureInfo.InvariantCulture.Clone();
formatProvider.TextInfo.ListSeparator = " ";
// Create square, symmetric, positive definite matrix
var matrix = new DenseMatrix(new[,] { { 2.0, 1.0 }, { 1.0, 2.0 } });
Console.WriteLine(@"Initial square, symmetric, positive definite matrix");
Console.WriteLine(matrix.ToString("#0.00\t", formatProvider));
Console.WriteLine();
// Perform Cholesky decomposition
var cholesky = matrix.Cholesky();
Console.WriteLine(@"Perform Cholesky decomposition");
// 1. Lower triangular form of the Cholesky matrix
Console.WriteLine(@"1. Lower triangular form of the Cholesky matrix");
Console.WriteLine(cholesky.Factor.ToString("#0.00\t", formatProvider));
Console.WriteLine();
// 2. Reconstruct initial matrix: A = L * LT
var reconstruct = cholesky.Factor * cholesky.Factor.Transpose();
Console.WriteLine(@"2. Reconstruct initial matrix: A = L*LT");
Console.WriteLine(reconstruct.ToString("#0.00\t", formatProvider));
Console.WriteLine();
// 3. Get determinant of the matrix
Console.WriteLine(@"3. Determinant of the matrix");
Console.WriteLine(cholesky.Determinant);
Console.WriteLine();
// 4. Get log determinant of the matrix
Console.WriteLine(@"4. Log determinant of the matrix");
Console.WriteLine(cholesky.DeterminantLn);
Console.WriteLine();
}
}
}

188
src/Examples/LinearAlgebra/Factorization/Evd.cs

@ -0,0 +1,188 @@
// <copyright file="Evd.cs" company="Math.NET">
// Math.NET Numerics, part of the Math.NET Project
// http://numerics.mathdotnet.com
// http://github.com/mathnet/mathnet-numerics
// http://mathnetnumerics.codeplex.com
// Copyright (c) 2009-2010 Math.NET
// Permission is hereby granted, free of charge, to any person
// obtaining a copy of this software and associated documentation
// files (the "Software"), to deal in the Software without
// restriction, including without limitation the rights to use,
// copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following
// conditions:
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
// OTHER DEALINGS IN THE SOFTWARE.
// </copyright>
namespace Examples.LinearAlgebra.Factorization
{
using System;
using System.Globalization;
using MathNet.Numerics.LinearAlgebra.Double;
using MathNet.Numerics.LinearAlgebra.Generic.Factorization;
/// <summary>
/// EVD factorization example. If A is symmetric, then A = V*D*V' where the eigenvalue matrix D is
/// diagonal and the eigenvector matrix V is orthogonal. I.e. A = V*D*V' and V*VT=I.
/// If A is not symmetric, then the eigenvalue matrix D is block diagonal
/// with the real eigenvalues in 1-by-1 blocks and any complex eigenvalues,
/// lambda + i*mu, in 2-by-2 blocks, [lambda, mu; -mu, lambda]. The
/// columns of V represent the eigenvectors in the sense thatA * V = V * D.
/// The matrix V may be badly conditioned, or even singular, so the validity of the equation
/// A = V*D*Inverse(V) depends upon V.Condition()
/// </summary>
/// <seealso cref="http://reference.wolfram.com/mathematica/ref/Norm.html"/>
public class Evd : IExample
{
/// <summary>
/// Gets the name of this example
/// </summary>
public string Name
{
get
{
return "Evd factorization";
}
}
/// <summary>
/// Gets the description of this example
/// </summary>
public string Description
{
get
{
return "Perform the Evd factorization: eigenvalues and eigenvectors calculation";
}
}
/// <summary>
/// Run example
/// </summary>
/// <seealso cref="http://en.wikipedia.org/wiki/Eigenvalue,_eigenvector_and_eigenspace">EVD decomposition</seealso>
public void Run()
{
// Format matrix output to console
var formatProvider = (CultureInfo)CultureInfo.InvariantCulture.Clone();
formatProvider.TextInfo.ListSeparator = " ";
// Create square symmetric matrix
var matrix = new DenseMatrix(new[,] { { 1.0, 2.0, 3.0 }, { 2.0, 1.0, 4.0 }, { 3.0, 4.0, 1.0 } });
Console.WriteLine(@"Initial square symmetric matrix");
Console.WriteLine(matrix.ToString("#0.00\t", formatProvider));
Console.WriteLine();
// Perform eigenvalue decomposition of symmetric matrix
var evd = matrix.Evd();
Console.WriteLine(@"Perform eigenvalue decomposition of symmetric matrix");
// 1. Eigen vectors
Console.WriteLine(@"1. Eigen vectors");
Console.WriteLine(evd.EigenVectors().ToString("#0.00\t", formatProvider));
Console.WriteLine();
// 2. Eigen values as a complex vector
Console.WriteLine(@"2. Eigen values as a complex vector");
Console.WriteLine(evd.EigenValues().ToString("N", formatProvider));
Console.WriteLine();
// 3. Eigen values as the block diagonal matrix
Console.WriteLine(@"3. Eigen values as the block diagonal matrix");
Console.WriteLine(evd.D().ToString("#0.00\t", formatProvider));
Console.WriteLine();
// 4. Multiply V by its transpose VT
var identity = evd.EigenVectors().TransposeAndMultiply(evd.EigenVectors());
Console.WriteLine(@"4. Multiply V by its transpose VT: V*VT = I");
Console.WriteLine(identity.ToString("#0.00\t", formatProvider));
Console.WriteLine();
// 5. Reconstruct initial matrix: A = V*D*V'
var reconstruct = evd.EigenVectors() * evd.D() * evd.EigenVectors().Transpose();
Console.WriteLine(@"5. Reconstruct initial matrix: A = V*D*V'");
Console.WriteLine(reconstruct.ToString("#0.00\t", formatProvider));
Console.WriteLine();
// 6. Determinant of the matrix
Console.WriteLine(@"6. Determinant of the matrix");
Console.WriteLine(evd.Determinant);
Console.WriteLine();
// 7. Rank of the matrix
Console.WriteLine(@"7. Rank of the matrix");
Console.WriteLine(evd.Rank);
Console.WriteLine();
// Fill matrix by random values
var rnd = new Random(1);
for (var i = 0; i < matrix.RowCount; i++)
{
for (var j = 0; j < matrix.ColumnCount; j++)
{
matrix[i, j] = rnd.NextDouble();
}
}
Console.WriteLine(@"Fill matrix by random values");
Console.WriteLine(matrix.ToString("#0.00\t", formatProvider));
Console.WriteLine();
// Perform eigenvalue decomposition of non-symmetric matrix
evd = matrix.Evd();
Console.WriteLine(@"Perform eigenvalue decomposition of non-symmetric matrix");
// 8. Eigen vectors
Console.WriteLine(@"8. Eigen vectors");
Console.WriteLine(evd.EigenVectors().ToString("#0.00\t", formatProvider));
Console.WriteLine();
// 9. Eigen values as a complex vector
Console.WriteLine(@"9. Eigen values as a complex vector");
Console.WriteLine(evd.EigenValues().ToString("N", formatProvider));
Console.WriteLine();
// 10. Eigen values as the block diagonal matrix
Console.WriteLine(@"10. Eigen values as the block diagonal matrix");
Console.WriteLine(evd.D().ToString("#0.00\t", formatProvider));
Console.WriteLine();
// 11. Multiply A * V
var av = matrix * evd.EigenVectors();
Console.WriteLine(@"11. Multiply A * V");
Console.WriteLine(av.ToString("#0.00\t", formatProvider));
Console.WriteLine();
// 12. Multiply V * D
var vd = evd.EigenVectors() * evd.D();
Console.WriteLine(@"12. Multiply V * D");
Console.WriteLine(vd.ToString("#0.00\t", formatProvider));
Console.WriteLine();
// 13. Reconstruct non-symmetriv matrix A = V * D * Vinverse
reconstruct = evd.EigenVectors() * evd.D() * evd.EigenVectors().Inverse();
Console.WriteLine(@"13. Reconstruct non-symmetriv matrix A = V * D * Vinverse");
Console.WriteLine(reconstruct.ToString("#0.00\t", formatProvider));
Console.WriteLine();
// 14. Determinant of the matrix
Console.WriteLine(@"14. Determinant of the matrix");
Console.WriteLine(evd.Determinant);
Console.WriteLine();
// 15. Rank of the matrix
Console.WriteLine(@"15. Rank of the matrix");
Console.WriteLine(evd.Rank);
Console.WriteLine();
}
}
}

135
src/Examples/LinearAlgebra/Factorization/LU.cs

@ -0,0 +1,135 @@
// <copyright file="LU.cs" company="Math.NET">
// Math.NET Numerics, part of the Math.NET Project
// http://numerics.mathdotnet.com
// http://github.com/mathnet/mathnet-numerics
// http://mathnetnumerics.codeplex.com
// Copyright (c) 2009-2010 Math.NET
// Permission is hereby granted, free of charge, to any person
// obtaining a copy of this software and associated documentation
// files (the "Software"), to deal in the Software without
// restriction, including without limitation the rights to use,
// copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following
// conditions:
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
// OTHER DEALINGS IN THE SOFTWARE.
// </copyright>
namespace Examples.LinearAlgebra.Factorization
{
using System;
using System.Globalization;
using MathNet.Numerics.LinearAlgebra.Double;
using MathNet.Numerics.LinearAlgebra.Generic.Factorization;
/// <summary>
/// LU factorization example. For a matrix A, the LU factorization is a pair of lower triangular matrix L and
/// upper triangular matrix U so that A = L*U.
/// In the Math.Net implementation we also store a set of pivot elements for increased
/// numerical stability. The pivot elements encode a permutation matrix P such that P*A = L*U
/// </summary>
/// <seealso cref="http://reference.wolfram.com/mathematica/ref/LUDecomposition.html"/>
public class LU : IExample
{
/// <summary>
/// Gets the name of this example
/// </summary>
public string Name
{
get
{
return "LU factorization";
}
}
/// <summary>
/// Gets the description of this example
/// </summary>
public string Description
{
get
{
return "Perform the LU factorization to the appropriate class";
}
}
/// <summary>
/// Run example
/// </summary>
/// <seealso cref="http://en.wikipedia.org/wiki/LU_decomposition">LU decomposition</seealso>
/// <seealso cref="http://en.wikipedia.org/wiki/Invertible_matrix">Invertible matrix</seealso>
public void Run()
{
// Format matrix output to console
var formatProvider = (CultureInfo)CultureInfo.InvariantCulture.Clone();
formatProvider.TextInfo.ListSeparator = " ";
// Create square matrix
var matrix = new DenseMatrix(new[,] { { 1.0, 2.0 }, { 3.0, 4.0 } });
Console.WriteLine(@"Initial square matrix");
Console.WriteLine(matrix.ToString("#0.00\t", formatProvider));
Console.WriteLine();
// Perform LU decomposition
var lu = matrix.LU();
Console.WriteLine(@"Perform LU decomposition");
// 1. Lower triangular factor
Console.WriteLine(@"1. Lower triangular factor");
Console.WriteLine(lu.L.ToString("#0.00\t", formatProvider));
Console.WriteLine();
// 2. Upper triangular factor
Console.WriteLine(@"2. Upper triangular factor");
Console.WriteLine(lu.U.ToString("#0.00\t", formatProvider));
Console.WriteLine();
// 3. Permutations applied to LU factorization
Console.WriteLine(@"3. Permutations applied to LU factorization");
for (var i = 0; i < lu.P.Dimension; i++)
{
if (lu.P[i] > i)
{
Console.WriteLine(@"Row {0} permuted with row {1}", lu.P[i], i);
}
}
Console.WriteLine();
// 4. Reconstruct initial matrix: PA = L * U
var reconstruct = lu.L * lu.U;
// The rows of the reconstructed matrix should be permuted to get the initial matrix
reconstruct.PermuteRows(lu.P.Inverse());
Console.WriteLine(@"4. Reconstruct initial matrix: PA = L*U");
Console.WriteLine(reconstruct.ToString("#0.00\t", formatProvider));
Console.WriteLine();
// 5. Get the determinant of the matrix
Console.WriteLine(@"5. Determinant of the matrix");
Console.WriteLine(lu.Determinant);
Console.WriteLine();
// 6. Get the inverse of the matrix
var matrixInverse = lu.Inverse();
Console.WriteLine(@"6. Inverse of the matrix");
Console.WriteLine(matrixInverse.ToString("#0.00\t", formatProvider));
Console.WriteLine();
// 7. Matrix multiplied by its inverse
var identity = matrix * matrixInverse;
Console.WriteLine(@"7. Matrix multiplied by its inverse ");
Console.WriteLine(identity.ToString("#0.00\t", formatProvider));
Console.WriteLine();
}
}
}

132
src/Examples/LinearAlgebra/Factorization/QR.cs

@ -0,0 +1,132 @@
// <copyright file="QR.cs" company="Math.NET">
// Math.NET Numerics, part of the Math.NET Project
// http://numerics.mathdotnet.com
// http://github.com/mathnet/mathnet-numerics
// http://mathnetnumerics.codeplex.com
// Copyright (c) 2009-2010 Math.NET
// Permission is hereby granted, free of charge, to any person
// obtaining a copy of this software and associated documentation
// files (the "Software"), to deal in the Software without
// restriction, including without limitation the rights to use,
// copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following
// conditions:
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
// OTHER DEALINGS IN THE SOFTWARE.
// </copyright>
namespace Examples.LinearAlgebra.Factorization
{
using System;
using System.Globalization;
using MathNet.Numerics.LinearAlgebra.Double;
using MathNet.Numerics.LinearAlgebra.Generic.Factorization;
/// <summary>
/// QR factorization example. Any real square matrix A (m x n) may be decomposed as A = QR where Q is an orthogonal matrix (m x m)
/// (its columns are orthogonal unit vectors meaning QTQ = I) and R (m x n) is an upper triangular matrix
/// (also called right triangular matrix).
/// In this example two methods for actually computing the QR decomposition presented: by means of the Gram–Schmidt process and Householder transformations.
/// </summary>
/// <seealso cref="http://reference.wolfram.com/mathematica/ref/QRDecomposition.html"/>
public class QR : IExample
{
/// <summary>
/// Gets the name of this example
/// </summary>
public string Name
{
get
{
return "QR factorization";
}
}
/// <summary>
/// Gets the description of this example
/// </summary>
public string Description
{
get
{
return "Perform the QR factorization by means of the Gram–Schmidt process and Householder transformations";
}
}
/// <summary>
/// Run example
/// </summary>
/// <seealso cref="http://en.wikipedia.org/wiki/QR_decomposition">QR decomposition</seealso>
public void Run()
{
// Format matrix output to console
var formatProvider = (CultureInfo)CultureInfo.InvariantCulture.Clone();
formatProvider.TextInfo.ListSeparator = " ";
// Create 3 x 2 matrix
var matrix = new DenseMatrix(new[,] { { 1.0, 2.0 }, { 3.0, 4.0 }, { 5.0, 6.0 } });
Console.WriteLine(@"Initial 3x2 matrix");
Console.WriteLine(matrix.ToString("#0.00\t", formatProvider));
Console.WriteLine();
// Perform QR decomposition (Householder transformations)
var qr = matrix.QR();
Console.WriteLine(@"QR decomposition (Householder transformations)");
// 1. Orthogonal Q matrix
Console.WriteLine(@"1. Orthogonal Q matrix");
Console.WriteLine(qr.Q.ToString("#0.00\t", formatProvider));
Console.WriteLine();
// 2. Multiply Q matrix by its transpose gives identity matrix
Console.WriteLine(@"2. Multiply Q matrix by its transpose gives identity matrix");
Console.WriteLine(qr.Q.TransposeAndMultiply(qr.Q).ToString("#0.00\t", formatProvider));
Console.WriteLine();
// 3. Upper triangular factor R
Console.WriteLine(@"3. Upper triangular factor R");
Console.WriteLine(qr.R.ToString("#0.00\t", formatProvider));
Console.WriteLine();
// 4. Reconstruct initial matrix: A = Q * R
var reconstruct = qr.Q * qr.R;
Console.WriteLine(@"4. Reconstruct initial matrix: A = Q*R");
Console.WriteLine(reconstruct.ToString("#0.00\t", formatProvider));
Console.WriteLine();
// Perform QR decomposition (Gram–Schmidt process)
qr = matrix.GramSchmidt();
Console.WriteLine(@"QR decomposition (Gram–Schmidt process)");
// 5. Orthogonal Q matrix
Console.WriteLine(@"5. Orthogonal Q matrix");
Console.WriteLine(qr.Q.ToString("#0.00\t", formatProvider));
Console.WriteLine();
// 6. Multiply Q matrix by its transpose gives identity matrix
Console.WriteLine(@"6. Multiply Q matrix by its transpose gives identity matrix");
Console.WriteLine((qr.Q.Transpose() * qr.Q).ToString("#0.00\t", formatProvider));
Console.WriteLine();
// 7. Upper triangular factor R
Console.WriteLine(@"7. Upper triangular factor R");
Console.WriteLine(qr.R.ToString("#0.00\t", formatProvider));
Console.WriteLine();
// 8. Reconstruct initial matrix: A = Q * R
reconstruct = qr.Q * qr.R;
Console.WriteLine(@"8. Reconstruct initial matrix: A = Q*R");
Console.WriteLine(reconstruct.ToString("#0.00\t", formatProvider));
Console.WriteLine();
}
}
}

186
src/Examples/LinearAlgebra/Factorization/Svd.cs

@ -0,0 +1,186 @@
// <copyright file="Svd.cs" company="Math.NET">
// Math.NET Numerics, part of the Math.NET Project
// http://numerics.mathdotnet.com
// http://github.com/mathnet/mathnet-numerics
// http://mathnetnumerics.codeplex.com
// Copyright (c) 2009-2010 Math.NET
// Permission is hereby granted, free of charge, to any person
// obtaining a copy of this software and associated documentation
// files (the "Software"), to deal in the Software without
// restriction, including without limitation the rights to use,
// copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following
// conditions:
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
// OTHER DEALINGS IN THE SOFTWARE.
// </copyright>
namespace Examples.LinearAlgebra.Factorization
{
using System;
using System.Globalization;
using MathNet.Numerics.LinearAlgebra.Double;
using MathNet.Numerics.LinearAlgebra.Generic.Factorization;
/// <summary>
/// SVD factorization example. Suppose M is an m-by-n matrix whose entries are real numbers.
/// Then there exists a factorization of the form M = UΣVT where:
/// - U is an m-by-m unitary matrix;
/// - Σ is m-by-n diagonal matrix with nonnegative real numbers on the diagonal;
/// - VT denotes transpose of V, an n-by-n unitary matrix;
/// Such a factorization is called a singular-value decomposition of M. A common convention is to order the diagonal
/// entries Σ(i,i) in descending order. In this case, the diagonal matrix Σ is uniquely determined
/// by M (though the matrices U and V are not). The diagonal entries of Σ are known as the singular values of M.
/// </summary>
/// <seealso cref="http://reference.wolfram.com/mathematica/ref/SingularValueDecomposition.html"/>
public class Svd : IExample
{
/// <summary>
/// Gets the name of this example
/// </summary>
public string Name
{
get
{
return "Svd factorization";
}
}
/// <summary>
/// Gets the description of this example
/// </summary>
public string Description
{
get
{
return "Perform the Svd factorization";
}
}
/// <summary>
/// Run example
/// </summary>
/// <seealso cref="http://en.wikipedia.org/wiki/Singular_value_decomposition">SVD decomposition</seealso>
public void Run()
{
// Format matrix output to console
var formatProvider = (CultureInfo)CultureInfo.InvariantCulture.Clone();
formatProvider.TextInfo.ListSeparator = " ";
// Create square matrix
var matrix = new DenseMatrix(new[,] { { 4.0, 1.0 }, { 3.0, 2.0 } });
Console.WriteLine(@"Initial square matrix");
Console.WriteLine(matrix.ToString("#0.00\t", formatProvider));
Console.WriteLine();
// Perform full SVD decomposition
var svd = matrix.Svd(true);
Console.WriteLine(@"Perform full SVD decomposition");
// 1. Left singular vectors
Console.WriteLine(@"1. Left singular vectors");
Console.WriteLine(svd.U().ToString("#0.00\t", formatProvider));
Console.WriteLine();
// 2. Singular values as vector
Console.WriteLine(@"2. Singular values as vector");
Console.WriteLine(svd.S().ToString("#0.00\t", formatProvider));
Console.WriteLine();
// 3. Singular values as diagonal matrix
Console.WriteLine(@"3. Singular values as diagonal matrix");
Console.WriteLine(svd.W().ToString("#0.00\t", formatProvider));
Console.WriteLine();
// 4. Right singular vectors
Console.WriteLine(@"4. Right singular vectors");
Console.WriteLine(svd.VT().ToString("#0.00\t", formatProvider));
Console.WriteLine();
// 5. Multiply U matrix by its transpose
var identinty = svd.U() * svd.U().Transpose();
Console.WriteLine(@"5. Multiply U matrix by its transpose");
Console.WriteLine(identinty.ToString("#0.00\t", formatProvider));
Console.WriteLine();
// 6. Multiply V matrix by its transpose
identinty = svd.VT().TransposeAndMultiply(svd.VT());
Console.WriteLine(@"6. Multiply V matrix by its transpose");
Console.WriteLine(identinty.ToString("#0.00\t", formatProvider));
Console.WriteLine();
// 7. Reconstruct initial matrix: A = U*Σ*VT
var reconstruct = svd.U() * svd.W() * svd.VT();
Console.WriteLine(@"7. Reconstruct initial matrix: A = U*S*VT");
Console.WriteLine(reconstruct.ToString("#0.00\t", formatProvider));
Console.WriteLine();
// 8. Condition Number of the matrix
Console.WriteLine(@"8. Condition Number of the matrix");
Console.WriteLine(svd.ConditionNumber);
Console.WriteLine();
// 9. Determinant of the matrix
Console.WriteLine(@"9. Determinant of the matrix");
Console.WriteLine(svd.Determinant);
Console.WriteLine();
// 10. 2-norm of the matrix
Console.WriteLine(@"10. 2-norm of the matrix");
Console.WriteLine(svd.Norm2);
Console.WriteLine();
// 11. Rank of the matrix
Console.WriteLine(@"11. Rank of the matrix");
Console.WriteLine(svd.Rank);
Console.WriteLine();
// Perform partial SVD decomposition, without computing the singular U and VT vectors
svd = matrix.Svd(false);
Console.WriteLine(@"Perform partial SVD decomposition, without computing the singular U and VT vectors");
// 12. Singular values as vector
Console.WriteLine(@"12. Singular values as vector");
Console.WriteLine(svd.S().ToString("#0.00\t", formatProvider));
Console.WriteLine();
// 13. Singular values as diagonal matrix
Console.WriteLine(@"13. Singular values as diagonal matrix");
Console.WriteLine(svd.W().ToString("#0.00\t", formatProvider));
Console.WriteLine();
// 14. Access to left singular vectors when partial SVD decomposition was performed
try
{
Console.WriteLine(@"14. Access to left singular vectors when partial SVD decomposition was performed");
Console.WriteLine(svd.U().ToString("#0.00\t", formatProvider));
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
Console.WriteLine();
}
// 15. Access to right singular vectors when partial SVD decomposition was performed
try
{
Console.WriteLine(@"15. Access to right singular vectors when partial SVD decomposition was performed");
Console.WriteLine(svd.VT().ToString("#0.00\t", formatProvider));
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
Console.WriteLine();
}
}
}
}

246
src/Examples/LinearAlgebra/MatrixArithmeticOperations.cs

@ -0,0 +1,246 @@
// <copyright file="MatrixArithmeticOperations.cs" company="Math.NET">
// Math.NET Numerics, part of the Math.NET Project
// http://numerics.mathdotnet.com
// http://github.com/mathnet/mathnet-numerics
// http://mathnetnumerics.codeplex.com
// Copyright (c) 2009-2010 Math.NET
// Permission is hereby granted, free of charge, to any person
// obtaining a copy of this software and associated documentation
// files (the "Software"), to deal in the Software without
// restriction, including without limitation the rights to use,
// copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following
// conditions:
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
// OTHER DEALINGS IN THE SOFTWARE.
// </copyright>
namespace Examples.LinearAlgebra
{
using System;
using System.Globalization;
using MathNet.Numerics.LinearAlgebra.Double;
/// <summary>
/// Basic matrix arithmetic operations as "+", "-", "*", "/"
/// </summary>
/// <seealso cref="http://reference.wolfram.com/mathematica/tutorial/VectorsAndMatrices.html"/>
public class MatrixArithmeticOperations : IExample
{
/// <summary>
/// Gets the name of this example
/// </summary>
public string Name
{
get
{
return "Matrix Arithmetics";
}
}
/// <summary>
/// Gets the description of this example
/// </summary>
public string Description
{
get
{
return "Basic operations between matrix/matrix and matrix/vecor";
}
}
/// <summary>
/// Run example
/// </summary>
/// <seealso cref="http://en.wikipedia.org/wiki/Matrix_multiplication#Scalar_multiplication">Multiply matrix by scalar</seealso>
/// <seealso cref="http://reference.wolfram.com/mathematica/tutorial/MultiplyingVectorsAndMatrices.html">Multiply matrix by vector</seealso>
/// <seealso cref="http://en.wikipedia.org/wiki/Matrix_multiplication#Matrix_product">Multiply matrix by matrix</seealso>
/// <seealso cref="http://en.wikipedia.org/wiki/Matrix_multiplication#Hadamard_product">Pointwise multiplie matrix with another matrix</seealso>
/// <seealso cref="http://en.wikipedia.org/wiki/Matrix_%28mathematics%29#Basic_operations">Addition and subtraction</seealso>
public void Run()
{
// Initialize IFormatProvider to print matrix/vector data
var formatProvider = (CultureInfo)CultureInfo.InvariantCulture.Clone();
formatProvider.TextInfo.ListSeparator = " ";
// Create matrix "A"
var matrixA = new DenseMatrix(new[,] { { 1.0, 2.0, 3.0 }, { 4.0, 5.0, 6.0 }, { 7.0, 8.0, 9.0 } });
Console.WriteLine(@"Matrix A");
Console.WriteLine(matrixA.ToString("#0.00\t", formatProvider));
Console.WriteLine();
// Create matrix "B"
var matrixB = new DenseMatrix(new[,] { { 1.0, 3.0, 5.0 }, { 2.0, 4.0, 6.0 }, { 3.0, 5.0, 7.0 } });
Console.WriteLine(@"Matrix B");
Console.WriteLine(matrixB.ToString("#0.00\t", formatProvider));
Console.WriteLine();
// Multiply matrix by scalar
// 1. Using operator "*"
var resultM = 3.0 * matrixA;
Console.WriteLine(@"Multiply matrix by scalar using operator *. (result = 3.0 * A)");
Console.WriteLine(resultM.ToString("#0.00\t", formatProvider));
Console.WriteLine();
// 2. Using Multiply method and getting result into different matrix instance
resultM = matrixA.Multiply(3.0);
Console.WriteLine(@"Multiply matrix by scalar using method Multiply. (result = A.Multiply(3.0))");
Console.WriteLine(resultM.ToString("#0.00\t", formatProvider));
Console.WriteLine();
// 3. Using Multiply method and updating matrix itself
matrixA.Multiply(3.0, matrixA);
Console.WriteLine(@"Multiply matrix by scalar using method Multiply. (A.Multiply(3.0, A))");
Console.WriteLine(matrixA.ToString("#0.00\t", formatProvider));
Console.WriteLine();
// Multiply matrix by vector (right-multiply)
var vector = new DenseVector(new[] { 1.0, 2.0, 3.0 });
Console.WriteLine(@"Vector");
Console.WriteLine(vector.ToString("#0.00\t", formatProvider));
Console.WriteLine();
// 1. Using operator "*"
var resultV = matrixA * vector;
Console.WriteLine(@"Multiply matrix by vector using operator *. (result = A * vec)");
Console.WriteLine(resultV.ToString("#0.00\t", formatProvider));
Console.WriteLine();
// 2. Using Multiply method and getting result into different vector instance
resultV = matrixA.Multiply(vector);
Console.WriteLine(@"Multiply matrix by vector using method Multiply. (result = A.Multiply(vec))");
Console.WriteLine(resultV.ToString("#0.00\t", formatProvider));
Console.WriteLine();
// 3. Using Multiply method and updating vector itself
matrixA.Multiply(vector, vector);
Console.WriteLine(@"Multiply matrix by vector using method Multiply. (A.Multiply(vec, vec))");
Console.WriteLine(vector.ToString("#0.00\t", formatProvider));
Console.WriteLine();
// Multiply vector by matrix (left-multiply)
// 1. Using operator "*"
resultV = vector * matrixA;
Console.WriteLine(@"Multiply vector by matrix using operator *. (result = vec * A)");
Console.WriteLine(resultV.ToString("#0.00\t", formatProvider));
Console.WriteLine();
// 2. Using LeftMultiply method and getting result into different vector instance
resultV = matrixA.LeftMultiply(vector);
Console.WriteLine(@"Multiply vector by matrix using method LeftMultiply. (result = A.LeftMultiply(vec))");
Console.WriteLine(resultV.ToString("#0.00\t", formatProvider));
Console.WriteLine();
// 3. Using LeftMultiply method and updating vector itself
matrixA.LeftMultiply(vector, vector);
Console.WriteLine(@"Multiply vector by matrix using method LeftMultiply. (A.LeftMultiply(vec, vec))");
Console.WriteLine(vector.ToString("#0.00\t", formatProvider));
Console.WriteLine();
// Multiply matrix by matrix
// 1. Using operator "*"
resultM = matrixA * matrixB;
Console.WriteLine(@"Multiply matrix by matrix using operator *. (result = A * B)");
Console.WriteLine(resultM.ToString("#0.00\t", formatProvider));
Console.WriteLine();
// 2. Using Multiply method and getting result into different matrix instance
resultM = matrixA.Multiply(matrixB);
Console.WriteLine(@"Multiply matrix by matrix using method Multiply. (result = A.Multiply(B))");
Console.WriteLine(resultM.ToString("#0.00\t", formatProvider));
Console.WriteLine();
// 3. Using Multiply method and updating matrix itself
matrixA.Multiply(matrixB, matrixA);
Console.WriteLine(@"Multiply matrix by matrix using method Multiply. (A.Multiply(B, A))");
Console.WriteLine(matrixA.ToString("#0.00\t", formatProvider));
Console.WriteLine();
// Pointwise multiplie matrix with another matrix
// 1. Using PointwiseMultiply method and getting result into different matrix instance
resultM = matrixA.PointwiseMultiply(matrixB);
Console.WriteLine(@"Pointwise multiplie matrix with another matrix using method PointwiseMultiply. (result = A.PointwiseMultiply(B))");
Console.WriteLine(resultM.ToString("#0.00\t", formatProvider));
Console.WriteLine();
// 2. Using PointwiseMultiply method and updating matrix itself
matrixA.PointwiseMultiply(matrixB, matrixA);
Console.WriteLine(@"Pointwise multiplie matrix with another matrix using method PointwiseMultiply. (A.PointwiseMultiply(B, A))");
Console.WriteLine(matrixA.ToString("#0.00\t", formatProvider));
Console.WriteLine();
// Pointwise divide matrix with another matrix
// 1. Using PointwiseDivide method and getting result into different matrix instance
resultM = matrixA.PointwiseDivide(matrixB);
Console.WriteLine(@"Pointwise divide matrix with another matrix using method PointwiseDivide. (result = A.PointwiseDivide(B))");
Console.WriteLine(resultM.ToString("#0.00\t", formatProvider));
Console.WriteLine();
// 2. Using PointwiseDivide method and updating matrix itself
matrixA.PointwiseDivide(matrixB, matrixA);
Console.WriteLine(@"Pointwise divide matrix with another matrix using method PointwiseDivide. (A.PointwiseDivide(B, A))");
Console.WriteLine(matrixA.ToString("#0.00\t", formatProvider));
Console.WriteLine();
// Addition
// 1. Using operator "+"
resultM = matrixA + matrixB;
Console.WriteLine(@"Add matrices using operator +. (result = A + B)");
Console.WriteLine(resultM.ToString("#0.00\t", formatProvider));
Console.WriteLine();
// 2. Using Add method and getting result into different matrix instance
resultM = matrixA.Add(matrixB);
Console.WriteLine(@"Add matrices using method Add. (result = A.Add(B))");
Console.WriteLine(resultM.ToString("#0.00\t", formatProvider));
Console.WriteLine();
// 3. Using Add method and updating matrix itself
matrixA.Add(matrixB, matrixA);
Console.WriteLine(@"Add matrices using method Add. (A.Add(B, A))");
Console.WriteLine(matrixA.ToString("#0.00\t", formatProvider));
Console.WriteLine();
// Subtraction
// 1. Using operator "-"
resultM = matrixA - matrixB;
Console.WriteLine(@"Subtract matrices using operator -. (result = A - B)");
Console.WriteLine(resultM.ToString("#0.00\t", formatProvider));
Console.WriteLine();
// 2. Using Subtract method and getting result into different matrix instance
resultM = matrixA.Subtract(matrixB);
Console.WriteLine(@"Subtract matrices using method Subtract. (result = A.Subtract(B))");
Console.WriteLine(resultM.ToString("#0.00\t", formatProvider));
Console.WriteLine();
// 3. Using Subtract method and updating matrix itself
matrixA.Subtract(matrixB, matrixA);
Console.WriteLine(@"Subtract matrices using method Subtract. (A.Subtract(B, A))");
Console.WriteLine(matrixA.ToString("#0.00\t", formatProvider));
Console.WriteLine();
// Divide by scalar
// 1. Using Divide method and getting result into different matrix instance
resultM = matrixA.Divide(3.0);
Console.WriteLine(@"Divide matrix by scalar using method Divide. (result = A.Divide(3.0))");
Console.WriteLine(resultM.ToString("#0.00\t", formatProvider));
Console.WriteLine();
// 2. Using Divide method and updating matrix itself
matrixA.Divide(3.0, matrixA);
Console.WriteLine(@"Divide matrix by scalar using method Divide. (A.Divide(3.0, A))");
Console.WriteLine(matrixA.ToString("#0.00\t", formatProvider));
Console.WriteLine();
}
}
}

208
src/Examples/LinearAlgebra/MatrixDataAccessor.cs

@ -0,0 +1,208 @@
// <copyright file="MatrixDataAccessor.cs" company="Math.NET">
// Math.NET Numerics, part of the Math.NET Project
// http://numerics.mathdotnet.com
// http://github.com/mathnet/mathnet-numerics
// http://mathnetnumerics.codeplex.com
// Copyright (c) 2009-2010 Math.NET
// Permission is hereby granted, free of charge, to any person
// obtaining a copy of this software and associated documentation
// files (the "Software"), to deal in the Software without
// restriction, including without limitation the rights to use,
// copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following
// conditions:
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
// OTHER DEALINGS IN THE SOFTWARE.
// </copyright>
namespace Examples.LinearAlgebra
{
using System;
using System.Globalization;
using MathNet.Numerics.LinearAlgebra.Double;
/// <summary>
/// Matrix data access, copying and conversion examples
/// </summary>
public class MatrixDataAccessor
{
/// <summary>
/// Gets the name of this example
/// </summary>
public string Name
{
get
{
return "Matrix data access, copying and conversion";
}
}
/// <summary>
/// Gets the description of this example
/// </summary>
public string Description
{
get
{
return "Examples of setting/getting values of a matrix, copying and conversion matrix into another matrix";
}
}
/// <summary>
/// Run example
/// </summary>
public void Run()
{
// Format vector output to console
var formatProvider = (CultureInfo)CultureInfo.InvariantCulture.Clone();
formatProvider.TextInfo.ListSeparator = " ";
// Create new empty square matrix
var matrix = new DenseMatrix(10);
Console.WriteLine(@"Empty matrix");
Console.WriteLine(matrix.ToString("#0.00\t", formatProvider));
Console.WriteLine();
// 1. Fill matrix by data using indexer []
var k = 0;
for (var i = 0; i < matrix.RowCount; i++)
{
for (var j = 0; j < matrix.ColumnCount; j++)
{
matrix[i, j] = k++;
}
}
Console.WriteLine(@"1. Fill matrix by data using indexer []");
Console.WriteLine(matrix.ToString("#0.00\t", formatProvider));
Console.WriteLine();
// 2. Fill matrix by data using At. The element is set without range checking.
for (var i = 0; i < matrix.RowCount; i++)
{
for (var j = 0; j < matrix.ColumnCount; j++)
{
matrix.At(i, j, k--);
}
}
Console.WriteLine(@"2. Fill matrix by data using At");
Console.WriteLine(matrix.ToString("#0.00\t", formatProvider));
Console.WriteLine();
// 3. Clone matrix
var clone = matrix.Clone();
Console.WriteLine(@"3. Clone matrix");
Console.WriteLine(clone.ToString("#0.00\t", formatProvider));
Console.WriteLine();
// 4. Clear matrix
clone.Clear();
Console.WriteLine(@"4. Clear matrix");
Console.WriteLine(clone.ToString("#0.00\t", formatProvider));
Console.WriteLine();
// 5. Copy matrix into another matrix
matrix.CopyTo(clone);
Console.WriteLine(@"5. Copy matrix into another matrix");
Console.WriteLine(clone.ToString("#0.00\t", formatProvider));
Console.WriteLine();
// 6. Get submatrix into another matrix
var submatrix = matrix.SubMatrix(2, 2, 3, 3);
Console.WriteLine(@"6. Copy submatrix into another matrix");
Console.WriteLine(submatrix.ToString("#0.00\t", formatProvider));
Console.WriteLine();
// 7. Get part of the row as vector. In this example: get 4 elements from row 5 starting from column 3
var row = matrix.Row(5, 3, 4);
Console.WriteLine(@"7. Get part of the row as vector");
Console.WriteLine(row.ToString("#0.00\t", formatProvider));
Console.WriteLine();
// 8. Get part of the column as vector. In this example: get 3 elements from column 2 starting from row 6
var column = matrix.Column(2, 6, 3);
Console.WriteLine(@"8. Get part of the column as vector");
Console.WriteLine(column.ToString("#0.00\t", formatProvider));
Console.WriteLine();
// 9. Get columns using column enumerator. If you need all columns you may use ColumnEnumerator without parameters
Console.WriteLine(@"9. Get columns using column enumerator");
foreach (var keyValuePair in matrix.ColumnEnumerator(2, 4))
{
Console.WriteLine(@"Column {0}: {1}", keyValuePair.Key, keyValuePair.Value.ToString("#0.00\t", formatProvider));
}
Console.WriteLine();
// 10. Get rows using row enumerator. If you need all rows you may use RowEnumerator without parameters
Console.WriteLine(@"10. Get rows using row enumerator");
foreach (var keyValuePair in matrix.RowEnumerator(4, 3))
{
Console.WriteLine(@"Row {0}: {1}", keyValuePair.Key, keyValuePair.Value.ToString("#0.00\t", formatProvider));
}
Console.WriteLine();
// 11. Convert matrix into multidimensional array
var data = matrix.ToArray();
Console.WriteLine(@"11. Convert matrix into multidimensional array");
for (var i = 0; i < data.GetLongLength(0); i++)
{
for (var j = 0; j < data.GetLongLength(1); j++)
{
Console.Write(data[i, j].ToString("#0.00\t"));
}
Console.WriteLine();
}
Console.WriteLine();
// 12. Convert matrix into row-wise array
var rowwise = matrix.ToRowWiseArray();
Console.WriteLine(@"12. Convert matrix into row-wise array");
for (var i = 0; i < matrix.RowCount; i++)
{
for (var j = 0; j < matrix.ColumnCount; j++)
{
Console.Write(rowwise[(i * matrix.ColumnCount) + j].ToString("#0.00\t"));
}
Console.WriteLine();
}
Console.WriteLine();
// 13. Convert matrix into column-wise array
var columnise = matrix.ToColumnWiseArray();
Console.WriteLine(@"13. Convert matrix into column-wise array");
for (var i = 0; i < matrix.RowCount; i++)
{
for (var j = 0; j < matrix.ColumnCount; j++)
{
Console.Write(columnise[(j * matrix.RowCount) + i].ToString("#0.00\t"));
}
Console.WriteLine();
}
Console.WriteLine();
// 14. Get matrix diagonal as vector
var diagonal = matrix.Diagonal();
Console.WriteLine(@"14. Get matrix diagonal as vector");
Console.WriteLine(diagonal.ToString("#0.00\t", formatProvider));
Console.WriteLine();
}
}
}

112
src/Examples/LinearAlgebra/MatrixInitialization.cs

@ -0,0 +1,112 @@
// <copyright file="MatrixInitialization.cs" company="Math.NET">
// Math.NET Numerics, part of the Math.NET Project
// http://numerics.mathdotnet.com
// http://github.com/mathnet/mathnet-numerics
// http://mathnetnumerics.codeplex.com
// Copyright (c) 2009-2010 Math.NET
// Permission is hereby granted, free of charge, to any person
// obtaining a copy of this software and associated documentation
// files (the "Software"), to deal in the Software without
// restriction, including without limitation the rights to use,
// copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following
// conditions:
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
// OTHER DEALINGS IN THE SOFTWARE.
// </copyright>
namespace Examples.LinearAlgebra
{
using System;
using System.Globalization;
using MathNet.Numerics.LinearAlgebra.Double;
/// <summary>
/// Matrix initialization examples
/// </summary>
public class MatrixInitialization : IExample
{
/// <summary>
/// Gets the name of this example
/// </summary>
public string Name
{
get
{
return "Matrix initialization";
}
}
/// <summary>
/// Gets the description of this example
/// </summary>
public string Description
{
get
{
return "Examples of creating matrix instances";
}
}
/// <summary>
/// Run example
/// </summary>
public void Run()
{
// 1. Initialize a new instance of the matrix from a 2D array. This constructor will allocate a completely new memory block for storing the dense matrix.
var matrix1 = new DenseMatrix(new[,] { { 1.0, 2.0, 3.0 }, { 4.0, 5.0, 6.0 } });
// 2. Initialize a new instance of the empty square matrix with a given order.
var matrix2 = new DenseMatrix(3);
// 3. Initialize a new instance of the empty matrix with a given size.
var matrix3 = new DenseMatrix(2, 3);
// 4. Initialize a new instance of the matrix with all entries set to a particular value.
var matrix4 = new DenseMatrix(2, 3, 3.0);
// 4. Initialize a new instance of the matrix from a one dimensional array. This array should store the matrix in column-major order.
var matrix5 = new DenseMatrix(2, 3, new[] { 1.0, 4.0, 2.0, 5.0, 3.0, 6.0 });
// 5. Initialize a square matrix with all zero's except for ones on the diagonal. Identity matrix (http://en.wikipedia.org/wiki/Identity_matrix).
var matrixI = DenseMatrix.Identity(5);
// Format matrix output to console
var formatProvider = (CultureInfo)CultureInfo.InvariantCulture.Clone();
formatProvider.TextInfo.ListSeparator = " ";
Console.WriteLine(@"Matrix 1");
Console.WriteLine(matrix1.ToString("#0.00\t", formatProvider));
Console.WriteLine();
Console.WriteLine(@"Matrix 2");
Console.WriteLine(matrix2.ToString("#0.00\t", formatProvider));
Console.WriteLine();
Console.WriteLine(@"Matrix 3");
Console.WriteLine(matrix3.ToString("#0.00\t", formatProvider));
Console.WriteLine();
Console.WriteLine(@"Matrix 4");
Console.WriteLine(matrix4.ToString("#0.00\t", formatProvider));
Console.WriteLine();
Console.WriteLine(@"Matrix 5");
Console.WriteLine(matrix5.ToString("#0.00\t", formatProvider));
Console.WriteLine();
Console.WriteLine(@"Identity matrix");
Console.WriteLine(matrixI.ToString("#0.00\t", formatProvider));
Console.WriteLine();
}
}
}

129
src/Examples/LinearAlgebra/MatrixNorms.cs

@ -0,0 +1,129 @@
// <copyright file="MatrixNorms.cs" company="Math.NET">
// Math.NET Numerics, part of the Math.NET Project
// http://numerics.mathdotnet.com
// http://github.com/mathnet/mathnet-numerics
// http://mathnetnumerics.codeplex.com
// Copyright (c) 2009-2010 Math.NET
// Permission is hereby granted, free of charge, to any person
// obtaining a copy of this software and associated documentation
// files (the "Software"), to deal in the Software without
// restriction, including without limitation the rights to use,
// copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following
// conditions:
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
// OTHER DEALINGS IN THE SOFTWARE.
// </copyright>
namespace Examples.LinearAlgebra
{
using System;
using System.Globalization;
using MathNet.Numerics.LinearAlgebra.Double;
/// <summary>
/// Matrix norms
/// </summary>
public class MatrixNorms : IExample
{
/// <summary>
/// Gets the name of this example
/// </summary>
public string Name
{
get
{
return "Matrix norms";
}
}
/// <summary>
/// Gets the description of this example
/// </summary>
public string Description
{
get
{
return "Examples of matrix norms: L1 norm, L2 norm, Frobenius norm and infinity norm";
}
}
/// <summary>
/// Run example
/// </summary>
/// <seealso cref="http://en.wikipedia.org/wiki/Matrix_norm">Matrix norm</seealso>
public void Run()
{
// Format matrix output to console
var formatProvider = (CultureInfo)CultureInfo.InvariantCulture.Clone();
formatProvider.TextInfo.ListSeparator = " ";
// Create square matrix
var matrix = new DenseMatrix(new[,] { { 1.0, 2.0, 3.0 }, { 6.0, 5.0, 4.0 }, { 8.0, 9.0, 7.0 } });
Console.WriteLine(@"Initial square matrix");
Console.WriteLine(matrix.ToString("#0.00\t", formatProvider));
Console.WriteLine();
// 1. 1-norm of the matrix
Console.WriteLine(@"1. 1-norm of the matrix");
Console.WriteLine(matrix.L1Norm());
Console.WriteLine();
// 2. 2-norm of the matrix
Console.WriteLine(@"2. 2-norm of the matrix");
Console.WriteLine(matrix.L2Norm());
Console.WriteLine();
// 3. Frobenius norm of the matrix
Console.WriteLine(@"3. Frobenius norm of the matrix");
Console.WriteLine(matrix.FrobeniusNorm());
Console.WriteLine();
// 4. Infinity norm of the matrix
Console.WriteLine(@"4. Infinity norm of the matrix");
Console.WriteLine(matrix.InfinityNorm());
Console.WriteLine();
// 5. Normalize matrix columns
Console.WriteLine(@"5. Normalize matrix columns: before normalize");
foreach (var keyValuePair in matrix.ColumnEnumerator())
{
Console.WriteLine(@"Column {0} 2-nd norm is: {1}", keyValuePair.Key, keyValuePair.Value.Norm(2));
}
Console.WriteLine();
var normalized = matrix.NormalizeColumns(2);
Console.WriteLine(@"5. Normalize matrix columns: after normalize");
foreach (var keyValuePair in normalized.ColumnEnumerator())
{
Console.WriteLine(@"Column {0} 2-nd norm is: {1}", keyValuePair.Key, keyValuePair.Value.Norm(2));
}
Console.WriteLine();
// 6. Normalize matrix columns
Console.WriteLine(@"6. Normalize matrix rows: before normalize");
foreach (var keyValuePair in matrix.RowEnumerator())
{
Console.WriteLine(@"Row {0} 2-nd norm is: {1}", keyValuePair.Key, keyValuePair.Value.Norm(2));
}
Console.WriteLine();
normalized = matrix.NormalizeRows(2);
Console.WriteLine(@"6. Normalize matrix rows: after normalize");
foreach (var keyValuePair in normalized.RowEnumerator())
{
Console.WriteLine(@"Row {0} 2-nd norm is: {1}", keyValuePair.Key, keyValuePair.Value.Norm(2));
}
}
}
}

173
src/Examples/LinearAlgebra/MatrixRowColumnOperations.cs

@ -0,0 +1,173 @@
// <copyright file="MatrixRowColumnOperations.cs" company="Math.NET">
// Math.NET Numerics, part of the Math.NET Project
// http://numerics.mathdotnet.com
// http://github.com/mathnet/mathnet-numerics
// http://mathnetnumerics.codeplex.com
// Copyright (c) 2009-2010 Math.NET
// Permission is hereby granted, free of charge, to any person
// obtaining a copy of this software and associated documentation
// files (the "Software"), to deal in the Software without
// restriction, including without limitation the rights to use,
// copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following
// conditions:
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
// OTHER DEALINGS IN THE SOFTWARE.
// </copyright>
namespace Examples.LinearAlgebra
{
using System;
using System.Globalization;
using MathNet.Numerics;
using MathNet.Numerics.LinearAlgebra.Double;
/// <summary>
/// Matrix operations with rows and columns
/// </summary>
public class MatrixRowColumnOperations : IExample
{
/// <summary>
/// Gets the name of this example
/// </summary>
public string Name
{
get
{
return "Matrix row and column operations";
}
}
/// <summary>
/// Gets the description of this example
/// </summary>
public string Description
{
get
{
return "Examples of permuting, modifying, inserting columns and rows in a matrix";
}
}
/// <summary>
/// Run example
/// </summary>
public void Run()
{
// Format matrix output to console
var formatProvider = (CultureInfo)CultureInfo.InvariantCulture.Clone();
formatProvider.TextInfo.ListSeparator = " ";
// Create square matrix
var matrix = new DenseMatrix(5);
var k = 0;
for (var i = 0; i < matrix.RowCount; i++)
{
for (var j = 0; j < matrix.ColumnCount; j++)
{
matrix[i, j] = k++;
}
}
Console.WriteLine(@"Initial matrix");
Console.WriteLine(matrix.ToString("#0.00\t", formatProvider));
Console.WriteLine();
// Create vector
var vector = new DenseVector(new[] { 50.0, 51.0, 52.0, 53.0, 54.0 });
Console.WriteLine(@"Sample vector");
Console.WriteLine(vector.ToString("#0.00\t", formatProvider));
Console.WriteLine();
// 1. Insert new column
var result = matrix.InsertColumn(3, vector);
Console.WriteLine(@"1. Insert new column");
Console.WriteLine(result.ToString("#0.00\t", formatProvider));
Console.WriteLine();
// 2. Insert new row
result = matrix.InsertRow(3, vector);
Console.WriteLine(@"2. Insert new row");
Console.WriteLine(result.ToString("#0.00\t", formatProvider));
Console.WriteLine();
// 3. Set column values
matrix.SetColumn(2, (Vector)vector);
Console.WriteLine(@"3. Set column values");
Console.WriteLine(matrix.ToString("#0.00\t", formatProvider));
Console.WriteLine();
// 4. Set row values.
matrix.SetRow(3, (double[])vector);
Console.WriteLine(@"4. Set row values");
Console.WriteLine(matrix.ToString("#0.00\t", formatProvider));
Console.WriteLine();
// 5. Set diagonal values. SetRow/SetColumn/SetDiagonal accepts Vector and double[] as input parameter
matrix.SetDiagonal(new[] { 5.0, 4.0, 3.0, 2.0, 1.0 });
Console.WriteLine(@"5. Set diagonal values");
Console.WriteLine(matrix.ToString("#0.00\t", formatProvider));
Console.WriteLine();
// 6. Set submatrix values
matrix.SetSubMatrix(1, 3, 1, 3, DenseMatrix.Identity(3));
Console.WriteLine(@"6. Set submatrix values");
Console.WriteLine(matrix.ToString("#0.00\t", formatProvider));
Console.WriteLine();
// Permutations.
// Initialize a new instance of the Permutation class. An array represents where each integer is permuted too:
// indices[i] represents that integer "i" is permuted to location indices[i]
var permutations = new Permutation(new[] { 0, 1, 3, 2, 4 });
// 7. Permute rows 3 and 4
matrix.PermuteRows(permutations);
Console.WriteLine(@"7. Permute rows 3 and 4");
Console.WriteLine(matrix.ToString("#0.00\t", formatProvider));
Console.WriteLine();
// 8. Permute columns 1 and 2, 3 and 5
permutations = new Permutation(new[] { 1, 0, 4, 3, 2 });
matrix.PermuteColumns(permutations);
Console.WriteLine(@"8. Permute columns 1 and 2, 3 and 5");
Console.WriteLine(matrix.ToString("#0.00\t", formatProvider));
Console.WriteLine();
// 9. Concatenate the matrix with the given matrix
var append = matrix.Append(matrix);
// Concatenate into result matrix
matrix.Append(matrix, append);
Console.WriteLine(@"9. Append matrix to matrix");
Console.WriteLine(append.ToString("#0.00\t", formatProvider));
Console.WriteLine();
// 10. Stack the matrix on top of the given matrix matrix
var stack = matrix.Stack(matrix);
// Stack into result matrix
matrix.Stack(matrix, stack);
Console.WriteLine(@"10. Stack the matrix on top of the given matrix matrix");
Console.WriteLine(stack.ToString("#0.00\t", formatProvider));
Console.WriteLine();
// 11. Diagonally stack the matrix on top of the given matrix matrix
var diagoinalStack = matrix.DiagonalStack(matrix);
// Diagonally stack into result matrix
matrix.DiagonalStack(matrix, diagoinalStack);
Console.WriteLine(@"11. Diagonally stack the matrix on top of the given matrix matrix");
Console.WriteLine(diagoinalStack.ToString("#0.00\t", formatProvider));
Console.WriteLine();
}
}
}

112
src/Examples/LinearAlgebra/MatrixSpecialNumbers.cs

@ -0,0 +1,112 @@
// <copyright file="MatrixSpecialNumbers.cs" company="Math.NET">
// Math.NET Numerics, part of the Math.NET Project
// http://numerics.mathdotnet.com
// http://github.com/mathnet/mathnet-numerics
// http://mathnetnumerics.codeplex.com
// Copyright (c) 2009-2010 Math.NET
// Permission is hereby granted, free of charge, to any person
// obtaining a copy of this software and associated documentation
// files (the "Software"), to deal in the Software without
// restriction, including without limitation the rights to use,
// copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following
// conditions:
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
// OTHER DEALINGS IN THE SOFTWARE.
// </copyright>
namespace Examples.LinearAlgebra
{
using System;
using System.Globalization;
using MathNet.Numerics.LinearAlgebra.Double;
/// <summary>
/// Special numbers associated with any square matrix
/// </summary>
/// <seealso cref="http://reference.wolfram.com/mathematica/ref/Det.html">The determinant of the square matrix</seealso>
/// <seealso cref="http://reference.wolfram.com/mathematica/ref/Tr.html">The trace of the matrix</seealso>
/// <seealso cref="http://reference.wolfram.com/mathematica/ref/MatrixRank.html">The rank of the matrix</seealso>
public class MatrixSpecialNumbers : IExample
{
/// <summary>
/// Gets the name of this example
/// </summary>
public string Name
{
get
{
return "Special numbers associated with any square matrix";
}
}
/// <summary>
/// Gets the description of this example
/// </summary>
public string Description
{
get
{
return "Matrix properties as: Determinant, Condition Number, Rank and Trace";
}
}
/// <summary>
/// Run example
/// </summary>
/// <seealso cref="http://en.wikipedia.org/wiki/Determinant">Determinant</seealso>
/// <seealso cref="http://en.wikipedia.org/wiki/Rank_%28linear_algebra%29">Rank (linear algebra)</seealso>
/// <seealso cref="http://en.wikipedia.org/wiki/Trace_%28linear_algebra%29">Trace (linear algebra)</seealso>
/// <seealso cref="http://en.wikipedia.org/wiki/Condition_number">Condition number</seealso>
public void Run()
{
// Format matrix output to console
var formatProvider = (CultureInfo)CultureInfo.InvariantCulture.Clone();
formatProvider.TextInfo.ListSeparator = " ";
// Create random square matrix
var matrix = new DenseMatrix(5);
var rnd = new Random(1);
for (var i = 0; i < matrix.RowCount; i++)
{
for (var j = 0; j < matrix.ColumnCount; j++)
{
matrix[i, j] = rnd.NextDouble();
}
}
Console.WriteLine(@"Initial matrix");
Console.WriteLine(matrix.ToString("#0.00\t", formatProvider));
Console.WriteLine();
// 1. Determinant
Console.WriteLine(@"1. Determinant");
Console.WriteLine(matrix.Determinant());
Console.WriteLine();
// 2. Rank
Console.WriteLine(@"2. Rank");
Console.WriteLine(matrix.Rank());
Console.WriteLine();
// 3. Condition number
Console.WriteLine(@"2. Condition number");
Console.WriteLine(matrix.ConditionNumber());
Console.WriteLine();
// 4. Trace
Console.WriteLine(@"4. Trace");
Console.WriteLine(matrix.Trace());
Console.WriteLine();
}
}
}

120
src/Examples/LinearAlgebra/MatrixTransposeAndInverse.cs

@ -0,0 +1,120 @@
// <copyright file="MatrixTransposeAndInverse.cs" company="Math.NET">
// Math.NET Numerics, part of the Math.NET Project
// http://numerics.mathdotnet.com
// http://github.com/mathnet/mathnet-numerics
// http://mathnetnumerics.codeplex.com
// Copyright (c) 2009-2010 Math.NET
// Permission is hereby granted, free of charge, to any person
// obtaining a copy of this software and associated documentation
// files (the "Software"), to deal in the Software without
// restriction, including without limitation the rights to use,
// copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following
// conditions:
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
// OTHER DEALINGS IN THE SOFTWARE.
// </copyright>
namespace Examples.LinearAlgebra
{
using System;
using System.Globalization;
using MathNet.Numerics.LinearAlgebra.Double;
using MathNet.Numerics.LinearAlgebra.Generic.Factorization;
/// <summary>
/// Matrix transpose and inverse
/// </summary>
/// <seealso cref="http://reference.wolfram.com/mathematica/ref/Transpose.html">Transpose</seealso>
/// <seealso cref="http://reference.wolfram.com/mathematica/ref/Inverse.html">Inverse</seealso>
public class MatrixTransposeAndInverse : IExample
{
/// <summary>
/// Gets the name of this example
/// </summary>
public string Name
{
get
{
return "Matrix transpose and inverse";
}
}
/// <summary>
/// Gets the description of this example
/// </summary>
public string Description
{
get
{
return "Transpose matrix, inverse matrix, transpose-and-multiply matrix examples";
}
}
/// <summary>
/// Run example
/// </summary>
/// <seealso cref="http://en.wikipedia.org/wiki/Transpose">Transpose</seealso>
/// <seealso cref="http://en.wikipedia.org/wiki/Invertible_matrix">Invertible matrix</seealso>
public void Run()
{
// Format matrix output to console
var formatProvider = (CultureInfo)CultureInfo.InvariantCulture.Clone();
formatProvider.TextInfo.ListSeparator = " ";
// Create random square matrix
var matrix = new DenseMatrix(5);
var rnd = new Random(1);
for (var i = 0; i < matrix.RowCount; i++)
{
for (var j = 0; j < matrix.ColumnCount; j++)
{
matrix[i, j] = rnd.NextDouble();
}
}
Console.WriteLine(@"Initial matrix");
Console.WriteLine(matrix.ToString("#0.00\t", formatProvider));
Console.WriteLine();
// 1. Get matrix inverse
var inverse = matrix.Inverse();
Console.WriteLine(@"1. Matrix inverse");
Console.WriteLine(inverse.ToString("#0.00\t", formatProvider));
Console.WriteLine();
// 2. Matrix multiplied by its inverse gives identity matrix
var identity = matrix * inverse;
Console.WriteLine(@"2. Matrix multiplied by its inverse");
Console.WriteLine(identity.ToString("#0.00\t", formatProvider));
Console.WriteLine();
// 3. Get matrix transpose
var transpose = matrix.Transpose();
Console.WriteLine(@"3. Matrix transpose");
Console.WriteLine(transpose.ToString("#0.00\t", formatProvider));
Console.WriteLine();
// 4. Get orthogonal matrix, i.e. do QR decomposition and get matrix Q
var orthogonal = matrix.QR().Q;
Console.WriteLine(@"4. Orthogonal matrix");
Console.WriteLine(orthogonal.ToString("#0.00\t", formatProvider));
Console.WriteLine();
// 5. Transpose and multiply orthogonal matrix by iteslf gives identity matrix
identity = orthogonal.TransposeAndMultiply(orthogonal);
Console.WriteLine(@"Transpose and multiply orthogonal matrix by iteslf");
Console.WriteLine(identity.ToString("#0.00\t", formatProvider));
Console.WriteLine();
}
}
}

123
src/Examples/LinearAlgebra/MatrixTriangular.cs

@ -0,0 +1,123 @@
// <copyright file="MatrixTriangular.cs" company="Math.NET">
// Math.NET Numerics, part of the Math.NET Project
// http://numerics.mathdotnet.com
// http://github.com/mathnet/mathnet-numerics
// http://mathnetnumerics.codeplex.com
// Copyright (c) 2009-2010 Math.NET
// Permission is hereby granted, free of charge, to any person
// obtaining a copy of this software and associated documentation
// files (the "Software"), to deal in the Software without
// restriction, including without limitation the rights to use,
// copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following
// conditions:
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
// OTHER DEALINGS IN THE SOFTWARE.
// </copyright>
namespace Examples.LinearAlgebra
{
using System;
using System.Globalization;
using MathNet.Numerics.LinearAlgebra.Double;
/// <summary>
/// Triangular matrices
/// </summary>
/// <seealso cref="http://reference.wolfram.com/mathematica/guide/PartsOfMatrices.html"/>
public class MatrixTriangular : IExample
{
/// <summary>
/// Gets the name of this example
/// </summary>
public string Name
{
get
{
return "Retrieving special forms of the matrix";
}
}
/// <summary>
/// Gets the description of this example
/// </summary>
public string Description
{
get
{
return "Retrieving different forms of triangular matrices from existing matrix";
}
}
/// <summary>
/// Run example
/// </summary>
/// <seealso cref="http://en.wikipedia.org/wiki/Triangular_matrix">Triangular matrix</seealso>
public void Run()
{
// Format matrix output to console
var formatProvider = (CultureInfo)CultureInfo.InvariantCulture.Clone();
formatProvider.TextInfo.ListSeparator = " ";
// Create square matrix
var matrix = new DenseMatrix(10);
var k = 0;
for (var i = 0; i < matrix.RowCount; i++)
{
for (var j = 0; j < matrix.ColumnCount; j++)
{
matrix[i, j] = k++;
}
}
Console.WriteLine(@"Initial square matrix");
Console.WriteLine(matrix.ToString("#0.00\t", formatProvider));
Console.WriteLine();
// 1. Retrieve a new matrix containing the lower triangle of the matrix
var lower = matrix.LowerTriangle();
// Puts the lower triangle of the matrix into the result matrix.
matrix.LowerTriangle(lower);
Console.WriteLine(@"1. Lower triangle of the matrix");
Console.WriteLine(lower.ToString("#0.00\t", formatProvider));
Console.WriteLine();
// 2. Retrieve a new matrix containing the upper triangle of the matrix
var upper = matrix.UpperTriangle();
// Puts the upper triangle of the matrix into the result matrix.
matrix.UpperTriangle(lower);
Console.WriteLine(@"2. Upper triangle of the matrix");
Console.WriteLine(upper.ToString("#0.00\t", formatProvider));
Console.WriteLine();
// 3. Retrieve a new matrix containing the strictly lower triangle of the matrix
var strictlylower = matrix.StrictlyLowerTriangle();
// Puts the strictly lower triangle of the matrix into the result matrix.
matrix.StrictlyLowerTriangle(strictlylower);
Console.WriteLine(@"3. Strictly lower triangle of the matrix");
Console.WriteLine(strictlylower.ToString("#0.00\t", formatProvider));
Console.WriteLine();
// 4. Retrieve a new matrix containing the strictly upper triangle of the matrix
var strictlyupper = matrix.StrictlyUpperTriangle();
// Puts the strictly upper triangle of the matrix into the result matrix.
matrix.StrictlyUpperTriangle(strictlyupper);
Console.WriteLine(@"4. Strictly upper triangle of the matrix");
Console.WriteLine(strictlyupper.ToString("#0.00\t", formatProvider));
Console.WriteLine();
}
}
}

209
src/Examples/LinearAlgebra/VectorArithmeticOperations.cs

@ -0,0 +1,209 @@
// <copyright file="VectorArithmeticOperations.cs" company="Math.NET">
// Math.NET Numerics, part of the Math.NET Project
// http://numerics.mathdotnet.com
// http://github.com/mathnet/mathnet-numerics
// http://mathnetnumerics.codeplex.com
// Copyright (c) 2009-2010 Math.NET
// Permission is hereby granted, free of charge, to any person
// obtaining a copy of this software and associated documentation
// files (the "Software"), to deal in the Software without
// restriction, including without limitation the rights to use,
// copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following
// conditions:
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
// OTHER DEALINGS IN THE SOFTWARE.
// </copyright>
namespace Examples.LinearAlgebra
{
using System;
using System.Globalization;
using MathNet.Numerics.LinearAlgebra.Double;
/// <summary>
/// Basic vector arithmetic operations as "+", "-", "*", "/"
/// </summary>
/// <seealso cref="http://reference.wolfram.com/mathematica/tutorial/VectorsAndMatrices.html"/>
public class VectorArithmeticOperations : IExample
{
/// <summary>
/// Gets the name of this example
/// </summary>
public string Name
{
get
{
return "Vector Arithmetics";
}
}
/// <summary>
/// Gets the description of this example
/// </summary>
public string Description
{
get
{
return "Basic operations between vector/vector and vector/matrix";
}
}
/// <summary>
/// Run example.
/// </summary>
/// <seealso cref="http://en.wikipedia.org/wiki/Euclidean_vector#Scalar_multiplication">Multiply vector by scalar</seealso>
/// <seealso cref="http://en.wikipedia.org/wiki/Euclidean_vector#Dot_product">Multiply vector by vector (compute the dot product between two vectors)</seealso>
/// <seealso cref="http://en.wikipedia.org/wiki/Euclidean_vector#Addition_and_subtraction">Vector addition and subtraction</seealso>
/// <seealso cref="http://en.wikipedia.org/wiki/Outer_product">Outer Product of two vectors</seealso>
public void Run()
{
// Initialize IFormatProvider to print matrix/vector data
var formatProvider = (CultureInfo)CultureInfo.InvariantCulture.Clone();
formatProvider.TextInfo.ListSeparator = " ";
// Create vector "X"
var vectorX = new DenseVector(new[] { 1.0, 2.0, 3.0, 4.0, 5.0 });
Console.WriteLine(@"Vector X");
Console.WriteLine(vectorX.ToString("#0.00\t", formatProvider));
Console.WriteLine();
// Create vector "Y"
var vectorY = new DenseVector(new[] { 5.0, 4.0, 3.0, 2.0, 1.0 });
Console.WriteLine(@"Vector Y");
Console.WriteLine(vectorY.ToString("#0.00\t", formatProvider));
Console.WriteLine();
// Multiply vector by scalar
// 1. Using Multiply method and getting result into different vector instance
var resultV = vectorX.Multiply(3.0);
Console.WriteLine(@"Multiply vector by scalar using method Multiply. (result = X.Multiply(3.0))");
Console.WriteLine(resultV.ToString("#0.00\t", formatProvider));
Console.WriteLine();
// 2. Using operator "*"
resultV = 3.0 * vectorX;
Console.WriteLine(@"Multiply vector by scalar using operator *. (result = 3.0 * X)");
Console.WriteLine(resultV.ToString("#0.00\t", formatProvider));
Console.WriteLine();
// 3. Using Multiply method and updating vector itself
vectorX.Multiply(3.0, vectorX);
Console.WriteLine(@"Multiply vector by scalar using method Multiply. (X.Multiply(3.0, X))");
Console.WriteLine(vectorX.ToString("#0.00\t", formatProvider));
Console.WriteLine();
// Multiply vector by vector (compute the dot product between two vectors)
// 1. Using operator "*"
var dotProduct = vectorX * vectorY;
Console.WriteLine(@"Dot product between two vectors using operator *. (result = X * Y)");
Console.WriteLine(dotProduct);
Console.WriteLine();
// 2. Using DotProduct method and getting result into different vector instance
dotProduct = vectorX.DotProduct(vectorY);
Console.WriteLine(@"Dot product between two vectors using method DotProduct. (result = X.DotProduct(Y))");
Console.WriteLine(dotProduct.ToString("#0.00\t", formatProvider));
Console.WriteLine();
// Pointwise multiplie vector with another vector
// 1. Using PointwiseMultiply method and getting result into different vector instance
resultV = vectorX.PointwiseMultiply(vectorY);
Console.WriteLine(@"Pointwise multiplie vector with another vector using method PointwiseMultiply. (result = X.PointwiseMultiply(Y))");
Console.WriteLine(resultV.ToString("#0.00\t", formatProvider));
Console.WriteLine();
// 2. Using PointwiseMultiply method and updating vector itself
vectorX.PointwiseMultiply(vectorY, vectorX);
Console.WriteLine(@"Pointwise multiplie vector with another vector using method PointwiseMultiply. (X.PointwiseMultiply(Y, X))");
Console.WriteLine(vectorX.ToString("#0.00\t", formatProvider));
Console.WriteLine();
// Pointwise divide vector with another vector
// 1. Using PointwiseDivide method and getting result into different vector instance
resultV = vectorX.PointwiseDivide(vectorY);
Console.WriteLine(@"Pointwise divide vector with another vector using method PointwiseDivide. (result = X.PointwiseDivide(Y))");
Console.WriteLine(resultV.ToString("#0.00\t", formatProvider));
Console.WriteLine();
// 2. Using PointwiseDivide method and updating vector itself
vectorX.PointwiseDivide(vectorY, vectorX);
Console.WriteLine(@"Pointwise divide vector with another vector using method PointwiseDivide. (X.PointwiseDivide(Y, X))");
Console.WriteLine(vectorX.ToString("#0.00\t", formatProvider));
Console.WriteLine();
// Addition
// 1. Using operator "+"
resultV = vectorX + vectorY;
Console.WriteLine(@"Add vectors using operator +. (result = X + Y)");
Console.WriteLine(resultV.ToString("#0.00\t", formatProvider));
Console.WriteLine();
// 2. Using Add method and getting result into different vector instance
resultV = vectorX.Add(vectorY);
Console.WriteLine(@"Add vectors using method Add. (result = X.Add(Y))");
Console.WriteLine(resultV.ToString("#0.00\t", formatProvider));
Console.WriteLine();
// 3. Using Add method and updating vector itself
vectorX.Add(vectorY, vectorX);
Console.WriteLine(@"Add vectors using method Add. (X.Add(Y, X))");
Console.WriteLine(vectorX.ToString("#0.00\t", formatProvider));
Console.WriteLine();
// Subtraction
// 1. Using operator "-"
resultV = vectorX - vectorY;
Console.WriteLine(@"Subtract vectors using operator -. (result = X - Y)");
Console.WriteLine(resultV.ToString("#0.00\t", formatProvider));
Console.WriteLine();
// 2. Using Subtract method and getting result into different vector instance
resultV = vectorX.Subtract(vectorY);
Console.WriteLine(@"Subtract vectors using method Subtract. (result = X.Subtract(Y))");
Console.WriteLine(resultV.ToString("#0.00\t", formatProvider));
Console.WriteLine();
// 3. Using Subtract method and updating vector itself
vectorX.Subtract(vectorY, vectorX);
Console.WriteLine(@"Subtract vectors using method Subtract. (X.Subtract(Y, X))");
Console.WriteLine(vectorX.ToString("#0.00\t", formatProvider));
Console.WriteLine();
// Divide by scalar
// 1. Using Divide method and getting result into different vector instance
resultV = vectorX.Divide(3.0);
Console.WriteLine(@"Divide vector by scalar using method Divide. (result = A.Divide(3.0))");
Console.WriteLine(resultV.ToString("#0.00\t", formatProvider));
Console.WriteLine();
// 2. Using Divide method and updating vector itself
vectorX.Divide(3.0, vectorX);
Console.WriteLine(@"Divide vector by scalar using method Divide. (X.Divide(3.0, X))");
Console.WriteLine(vectorX.ToString("#0.00\t", formatProvider));
Console.WriteLine();
// Outer Product of two vectors
// 1. Using instanse method OuterProduct
var resultM = vectorX.OuterProduct(vectorY);
Console.WriteLine(@"Outer Product of two vectors using method OuterProduct. (X.OuterProduct(Y))");
Console.WriteLine(resultM.ToString("#0.00\t", formatProvider));
Console.WriteLine();
// 2. Using static method of the Vector class
resultM = Vector.OuterProduct(vectorX, vectorY);
Console.WriteLine(@"Outer Product of two vectors using method OuterProduct. (Vector.OuterProduct(X,Y))");
Console.WriteLine(resultM.ToString("#0.00\t", formatProvider));
Console.WriteLine();
}
}
}

158
src/Examples/LinearAlgebra/VectorDataAccessor.cs

@ -0,0 +1,158 @@
// <copyright file="VectorDataAccessor.cs" company="Math.NET">
// Math.NET Numerics, part of the Math.NET Project
// http://numerics.mathdotnet.com
// http://github.com/mathnet/mathnet-numerics
// http://mathnetnumerics.codeplex.com
// Copyright (c) 2009-2010 Math.NET
// Permission is hereby granted, free of charge, to any person
// obtaining a copy of this software and associated documentation
// files (the "Software"), to deal in the Software without
// restriction, including without limitation the rights to use,
// copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following
// conditions:
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
// OTHER DEALINGS IN THE SOFTWARE.
// </copyright>
namespace Examples.LinearAlgebra
{
using System;
using System.Globalization;
using MathNet.Numerics.LinearAlgebra.Double;
/// <summary>
/// Vector data access, copying and conversion examples
/// </summary>
public class VectorDataAccessor
{
/// <summary>
/// Gets the name of this example
/// </summary>
public string Name
{
get
{
return "Vector data access, copying and conversion";
}
}
/// <summary>
/// Gets the description of this example
/// </summary>
public string Description
{
get
{
return "Examples of setting/getting values of a vector, copying and conversion vector into another vector";
}
}
/// <summary>
/// Run example
/// </summary>
public void Run()
{
// Format vector output to console
var formatProvider = (CultureInfo)CultureInfo.InvariantCulture.Clone();
formatProvider.TextInfo.ListSeparator = " ";
// Create new empty vector
var vectorA = new DenseVector(10);
Console.WriteLine(@"Empty vector A");
Console.WriteLine(vectorA.ToString("#0.00\t", formatProvider));
Console.WriteLine();
// 1. Fill vector by data using indexer []
for (var i = 0; i < vectorA.Count; i++)
{
vectorA[i] = i;
}
Console.WriteLine(@"1. Fill vector by data using indexer []");
Console.WriteLine(vectorA.ToString("#0.00\t", formatProvider));
Console.WriteLine();
// 2. Fill vector by data using SetValues method
vectorA.SetValues(new[] { 9.0, 8.0, 7.0, 6.0, 5.0, 4.0, 3.0, 2.0, 1.0, 0.0 });
Console.WriteLine(@"2. Fill vector by data using SetValues method");
Console.WriteLine(vectorA.ToString("#0.00\t", formatProvider));
Console.WriteLine();
// 3. Convert Vector to double[]
var data = vectorA.ToArray();
Console.WriteLine(@"3. Convert vector to double array");
for (var i = 0; i < data.Length; i++)
{
Console.Write(data[i].ToString("#0.00\t", formatProvider) + @" ");
}
Console.WriteLine();
Console.WriteLine();
// 4. Convert Vector to column matrix. A matrix based on this vector in column form (one single column)
var columnMatrix = vectorA.ToColumnMatrix();
Console.WriteLine(@"4. Convert vector to column matrix");
Console.WriteLine(columnMatrix.ToString("#0.00\t", formatProvider));
Console.WriteLine();
// 5. Convert Vector to row matrix. A matrix based on this vector in row form (one single row)
var rowMatrix = vectorA.ToRowMatrix();
Console.WriteLine(@"5. Convert vector to row matrix");
Console.WriteLine(rowMatrix.ToString("#0.00\t", formatProvider));
Console.WriteLine();
// 6. Clone vector
var cloneA = vectorA.Clone();
Console.WriteLine(@"6. Clone vector");
Console.WriteLine(cloneA.ToString("#0.00\t", formatProvider));
Console.WriteLine();
// 7. Clear vector
cloneA.Clear();
Console.WriteLine(@"7. Clear vector");
Console.WriteLine(cloneA.ToString("#0.00\t", formatProvider));
Console.WriteLine();
// 8. Copy part of vector into another vector. If you need to copy all data then use CopoTy(vector) method.
vectorA.CopyTo(cloneA, 3, 3, 4);
Console.WriteLine(@"8. Copy part of vector into another vector");
Console.WriteLine(cloneA.ToString("#0.00\t", formatProvider));
Console.WriteLine();
// 9. Get part of vector as another vector
var subvector = vectorA.SubVector(0, 5);
Console.WriteLine(@"9. Get subvector");
Console.WriteLine(subvector.ToString("#0.00\t", formatProvider));
Console.WriteLine();
// 10. Enumerator usage
Console.WriteLine(@"10. Enumerator usage");
foreach (var value in vectorA)
{
Console.Write(value.ToString("#0.00\t", formatProvider) + @" ");
}
Console.WriteLine();
Console.WriteLine();
// 11. Indexed enumerator usage
Console.WriteLine(@"11. Enumerator usage");
foreach (var value in vectorA.GetIndexedEnumerator())
{
Console.WriteLine(@"Index = {0}; Value = {1}", value.Key, value.Value.ToString("#0.00\t", formatProvider));
}
Console.WriteLine();
}
}
}

98
src/Examples/LinearAlgebra/VectorInitialization.cs

@ -0,0 +1,98 @@
// <copyright file="VectorInitialization.cs" company="Math.NET">
// Math.NET Numerics, part of the Math.NET Project
// http://numerics.mathdotnet.com
// http://github.com/mathnet/mathnet-numerics
// http://mathnetnumerics.codeplex.com
// Copyright (c) 2009-2010 Math.NET
// Permission is hereby granted, free of charge, to any person
// obtaining a copy of this software and associated documentation
// files (the "Software"), to deal in the Software without
// restriction, including without limitation the rights to use,
// copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following
// conditions:
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
// OTHER DEALINGS IN THE SOFTWARE.
// </copyright>
namespace Examples.LinearAlgebra
{
using System;
using System.Globalization;
using MathNet.Numerics.LinearAlgebra.Double;
/// <summary>
/// Vector initialization examples
/// </summary>
public class VectorInitialization : IExample
{
/// <summary>
/// Gets the name of this example
/// </summary>
public string Name
{
get
{
return "Vector initialization";
}
}
/// <summary>
/// Gets the description of this example
/// </summary>
public string Description
{
get
{
return "Examples of creating vector instances";
}
}
/// <summary>
/// Run example
/// </summary>
public void Run()
{
// 1. Initialize a new instance of the empty vector with a given size
var vector1 = new DenseVector(5);
// 2. Initialize a new instance of the vector with a given size and each element set to the given value
var vector2 = new DenseVector(5, 3.0);
// 3. Initialize a new instance of the vector from an array.
var vector3 = new DenseVector(new[] { 1.0, 2.0, 3.0, 4.0, 5.0 });
// 4. Initialize a new instance of the vector by copying the values from another.
var vector4 = new DenseVector(vector3);
// Format vector output to console
var formatProvider = (CultureInfo)CultureInfo.InvariantCulture.Clone();
formatProvider.TextInfo.ListSeparator = " ";
Console.WriteLine(@"Vector 1");
Console.WriteLine(vector1.ToString("#0.00\t", formatProvider));
Console.WriteLine();
Console.WriteLine(@"Vector 2");
Console.WriteLine(vector2.ToString("#0.00\t", formatProvider));
Console.WriteLine();
Console.WriteLine(@"Vector 3");
Console.WriteLine(vector3.ToString("#0.00\t", formatProvider));
Console.WriteLine();
Console.WriteLine(@"Vector 4");
Console.WriteLine(vector4.ToString("#0.00\t", formatProvider));
Console.WriteLine();
}
}
}

2
src/Numerics/LinearAlgebra/Generic/Matrix.cs

@ -1002,7 +1002,7 @@ namespace MathNet.Numerics.LinearAlgebra.Generic
result.SetRow(rowIndex, row);
for (var i = rowIndex + 1; i < RowCount; i++)
for (var i = rowIndex + 1; i < RowCount + 1; i++)
{
result.SetRow(i, Row(i - 1));
}

Loading…
Cancel
Save