### Compile and Run MKL Example Source: https://github.com/mathnet/mathnet-numerics/blob/master/docs/MKL.md This snippet shows how to compile a C# example using the MKL provider and then run the compiled executable. ```sh # single line: mcs -optimize -lib:packages/MathNet.Numerics.3.0.0-alpha8/lib/net40/ -r:MathNet.Numerics.dll Example.cs -out:Example # launch: mono Example ``` -------------------------------- ### Install Mono and F# on Debian/Ubuntu Source: https://github.com/mathnet/mathnet-numerics/blob/master/docs/index.md Installs Mono and F# on Debian-based systems using APT. This is a prerequisite for running Math.NET Numerics on Linux with Mono. ```sh sudo apt-get update sudo apt-get install mono-complete sudo apt-get install fsharp ``` -------------------------------- ### C# Example: Compare Managed vs. MKL Provider Performance Source: https://github.com/mathnet/mathnet-numerics/blob/master/docs/MKL.md A C# program demonstrating how to switch between the managed linear algebra provider and the Intel MKL native provider, and measuring the performance difference for a matrix solve operation. ```csharp using System; using System.Diagnostics; using MathNet.Numerics; using MathNet.Numerics.LinearAlgebra; class Program { static void Main(string[] args) { // Using managed code only Control.UseManaged(); Console.WriteLine(Control.LinearAlgebraProvider); var m = Matrix.Build.Random(500, 500); var v = Vector.Build.Random(500); var w = Stopwatch.StartNew(); var y1 = m.Solve(v); Console.WriteLine(w.Elapsed); Console.WriteLine(y1); // Using the Intel MKL native provider Control.UseNativeMKL(); Console.WriteLine(Control.LinearAlgebraProvider); w.Restart(); var y2 = m.Solve(v); Console.WriteLine(w.Elapsed); Console.WriteLine(y2); } } ``` -------------------------------- ### Install MKL NuGet Package on Linux Source: https://github.com/mathnet/mathnet-numerics/blob/master/docs/MKL.md Install the MathNet.Numerics MKL NuGet package for Linux using the Mono NuGet client. Specify the correct architecture (x64 or x86). ```sh mono nuget.exe install MathNet.Numerics -Pre -OutputDirectory packages mono nuget.exe install MathNet.Numerics.MKL.Linux-x64 -Pre -OutputDirectory packages ``` -------------------------------- ### Install Math.NET Numerics via NuGet Source: https://github.com/mathnet/mathnet-numerics/blob/master/docs/index.md Use this command to install the Math.NET Numerics package for C# projects. For F#, use the FSharp variant. ```sh mono nuget.exe install MathNet.Numerics -Pre -OutputDirectory packages # or if you intend to use F#: mono nuget.exe install MathNet.Numerics.FSharp -Pre -OutputDirectory packages ``` -------------------------------- ### Install/Migrate NuGet Packages with Paket Source: https://github.com/mathnet/mathnet-numerics/blob/master/docs/Build.md Install or migrate NuGet packages after modifying the 'paket.dependencies' file. Use this command to update dependencies. ```bash .paket/paket.exe install ``` -------------------------------- ### C# Setup for Random Number Generation Source: https://github.com/mathnet/mathnet-numerics/blob/master/docs/Random.md Include these namespaces to utilize Math.NET Numerics for random number generation and probability distributions in C#. ```csharp using MathNet.Numerics.Random; using MathNet.Numerics.Distributions; ``` -------------------------------- ### Build Intel MKL Provider for Windows Source: https://github.com/mathnet/mathnet-numerics/blob/master/docs/Build.md Triggers the build for both 32 and 64-bit variants of the Intel MKL native provider for Windows. Ensure Intel Parallel Studio or MKL and Visual Studio 2019 with C++ development workload are installed. ```bash ./build.sh MklWinBuild ``` -------------------------------- ### Example Output of Math.NET Numerics Program Source: https://github.com/mathnet/mathnet-numerics/blob/master/docs/index.md This is an example of the output produced by the C# program when evaluating a special function and solving a linear system. ```text 0.520499877813047 DenseVector 500-Double -0.181414 -1.25024 -0.607136 1.12975 -3.31201 0.344146 0.934095 -2.96364 1.84499 1.20752 0.753055 1.56942 0.472414 6.10418 -0.359401 0.613927 -0.140105 2.6079 0.163564 -3.04402 -0.350791 2.37228 -1.65218 -0.84056 1.51311 -2.17326 -0.220243 -0.0368934 -0.970052 0.580543 0.755483 -1.01755 -0.904162 -1.21824 -2.24888 1.42923 -0.971345 -3.16723 -0.822723 1.85148 -1.12235 -0.547885 -2.01044 4.06481 -0.128382 0.51167 -1.70276 ... ``` -------------------------------- ### Enable MKL Linear Algebra Provider Source: https://github.com/mathnet/mathnet-numerics/blob/master/docs/MKL.md Call this method to enable the MKL linear algebra provider. Ensure the necessary NuGet packages are installed and native libraries are accessible. ```csharp Control.UseNativeMKL(); ``` -------------------------------- ### Matrix Slicing and Submatrix Overwrite (F#) Source: https://github.com/mathnet/mathnet-numerics/blob/master/docs/Matrix.md Provides examples of F# slicing syntax for extracting row vectors and submatrices, as well as overwriting a submatrix with the contents of another matrix. ```fsharp let m = DenseMatrix.init 6 4 (fun i j -> float (10*i + j)) m.[0,0..3] // vector [0,1,2,3] m.[1..2,0..3] // matrix [10,11,12,13; 20,21,22,23] // overwrite a sub-matrix with the content of another matrix: m.[0..1,1..2] <- matrix [[ 3.0; 4.0 ]; [ 5.0; 6.0 ]] ``` -------------------------------- ### F# Other Random Generator Instantiation Source: https://github.com/mathnet/mathnet-numerics/blob/master/docs/Random.md Provides examples of instantiating other random number generators like Crypto, Xorshift, and WH2006 using the Random module in F#. ```fsharp // Using some other algorithms: let random3 = Random.crypto () let random4 = Random.xorshift () let random5 = Random.wh2006 () ``` -------------------------------- ### Full Documentation Build for Development Source: https://github.com/mathnet/mathnet-numerics/blob/master/docs/Build.md Perform a full, one-time documentation build with settings suitable for local development, including local/relative URIs. ```bash build.sh DocsDev ``` -------------------------------- ### Build Solution with .NET Core SDK Source: https://github.com/mathnet/mathnet-numerics/blob/master/docs/Build.md Build the Math.NET Numerics solution using the .NET Core SDK command-line tools. Ensure dependencies are restored first. ```bash dotnet build MathNet.Numerics.sln ``` -------------------------------- ### Full Release Build with FAKE Source: https://github.com/mathnet/mathnet-numerics/blob/master/docs/Build.md Perform a complete build process including building, testing, documentation, API reference generation, and packaging. This is used for creating releases. ```bash ./build.sh all ``` -------------------------------- ### Example Delimited Text Data Source: https://github.com/mathnet/mathnet-numerics/blob/master/docs/CSV.md A sample of data in a delimited text format, likely CSV. ```text A,B,C 0.5,0.6,98.0 2.0,3.4,5.3 ``` -------------------------------- ### Instantiate and Use Gamma Distribution (C#) Source: https://github.com/mathnet/mathnet-numerics/blob/master/docs/Probability.md Create a Gamma distribution instance to access its properties like mean and variance, and functions such as PDF, log-PDF, CDF, and sampling. Ensure MathNet.Numerics.Distributions and MathNet.Numerics.Random are imported. ```csharp using MathNet.Numerics.Distributions; using MathNet.Numerics.Random; // create a parametrized distribution instance var gamma = new Gamma(2.0, 1.5); // distribution properties double mean = gamma.Mean; double variance = gamma.Variance; double entropy = gamma.Entropy; // distribution functions double a = gamma.Density(2.3); // PDF double b = gamma.DensityLn(2.3); // ln(PDF) double c = gamma.CumulativeDistribution(0.7); // CDF // non-uniform number sampling double randomSample = gamma.Sample(); ``` -------------------------------- ### Create Matrix and Vector using Shortcuts Source: https://github.com/mathnet/mathnet-numerics/blob/master/docs/Matrix.md Shows how to define shortcuts for Matrix and Vector builders to shorten code. This is useful when frequently creating instances of the same data type. ```csharp var M = Matrix.Build; var V = Vector.Build; // build the same as above var m = M.Random(3, 4); var v = V.Dense(10); ``` -------------------------------- ### Build and Test Intel MKL Provider for Windows Source: https://github.com/mathnet/mathnet-numerics/blob/master/docs/Build.md Builds the Intel MKL provider for Windows and runs all associated tests. This provides a comprehensive check of the MKL integration. ```bash ./build.sh MklWinAll ``` -------------------------------- ### Create Decompositions using Instance Methods Source: https://github.com/mathnet/mathnet-numerics/wiki/Upgrading-to-Version-3 Use matrix instance methods like `QR` to create decompositions instead of manual construction. This is the recommended approach in v3. ```csharp Use matrix instance methods like QR to create decompositions, instead of constructing them manually. ``` -------------------------------- ### Use MKL in F# Interactive (with Reference Scripts) Source: https://github.com/mathnet/mathnet-numerics/blob/master/docs/MKL.md Automatically load the MKL provider using reference scripts in F# Interactive. Assumes MKL binaries are in the project directory or a subdirectory. ```fsharp open System.IO open MathNet.Numerics Control.NativeProviderPath <- Path.Combine(__SOURCE_DIRECTORY__,"../") Control.UseNativeMKL() ``` -------------------------------- ### Use Native MKL Provider Source: https://github.com/mathnet/mathnet-numerics/wiki/Upgrading-to-Version-3 If using the MKL native provider, it is recommended to use `Control.UseNativeMKL()` instead of manually creating a provider instance. ```csharp Control.UseNativeMKL() ``` -------------------------------- ### Build Math.NET Numerics with FAKE Source: https://github.com/mathnet/mathnet-numerics/blob/master/README.md Build the Math.NET Numerics project using FAKE build scripts. This is the recommended approach for building. ```bash ./build.sh build ./build.sh test ``` -------------------------------- ### Use MKL in F# Interactive (Basic) Source: https://github.com/mathnet/mathnet-numerics/blob/master/docs/MKL.md Set the native provider path and explicitly use the native MKL provider within F# Interactive. Assumes MKL binaries are in C:\MKL. ```fsharp Control.NativeProviderPath <- @"C:\MKL" Control.UseNativeMKL() ``` -------------------------------- ### Build Math.NET Numerics with .NET CLI Source: https://github.com/mathnet/mathnet-numerics/blob/master/README.md Build the Math.NET Numerics project using the .NET CLI. Ensure dependencies are restored first. ```bash ./restore.sh dotnet build MathNet.Numerics.sln ``` -------------------------------- ### Generate Documentation with FAKE Source: https://github.com/mathnet/mathnet-numerics/blob/master/docs/Build.md Generate the project documentation using the FAKE build script. This command processes CommonMark files to create HTML output. ```bash build.sh docs ``` -------------------------------- ### Build Math.NET Numerics with MsBuild/XBuild Source: https://github.com/mathnet/mathnet-numerics/blob/master/README.md Build the Math.NET Numerics project using MsBuild or XBuild. Dependency restoration is required beforehand. ```bash ./restore.sh msbuild MathNet.Numerics.sln ``` -------------------------------- ### Run FAKE Build Script (Linux/macOS/Bash on Windows) Source: https://github.com/mathnet/mathnet-numerics/blob/master/docs/Build.md Execute the FAKE build script for normal build and unit tests. This script automates various build tasks. ```bash ./build.sh ``` -------------------------------- ### Build Extra Packages Source: https://github.com/mathnet/mathnet-numerics/blob/master/docs/Build.md Use this command to build extra packages such as the Data Extensions. The prefix 'Data' is used for these packages. ```bash build.sh DataBuild ``` -------------------------------- ### Create Dense Matrix and Zero Vector Source: https://github.com/mathnet/mathnet-numerics/blob/master/docs/Matrix.md Demonstrates creating a dense matrix filled with random numbers and a dense zero-vector. Requires importing MathNet.Numerics.LinearAlgebra. ```csharp Matrix m = Matrix.Build.Random(3, 4); Vector v = Vector.Build.Dense(10); ``` -------------------------------- ### Test Intel MKL Provider for Windows Source: https://github.com/mathnet/mathnet-numerics/blob/master/docs/Build.md Runs all tests with the MKL provider enforced. This is useful for verifying the MKL integration. ```bash ./build.sh MklTest ``` -------------------------------- ### Run FAKE Build Script (Windows CMD) Source: https://github.com/mathnet/mathnet-numerics/blob/master/docs/Build.md Execute the FAKE build script for normal build and unit tests using the Windows Command Prompt. ```batch build.cmd ``` -------------------------------- ### Build MKL Provider on macOS Source: https://github.com/mathnet/mathnet-numerics/blob/master/docs/MKL.md Steps to build the MKL native provider on macOS using the provided shell script. Ensure you have a valid Intel MKL license. ```sh lionel:~ Lionel$ cd /Users/Lionel/Public/Git/GitHub/mathnet-numerics/src/NativeProviders/OSX lionel:OSX Lionel$ ls mkl_build.sh lionel:OSX Lionel$ sh mkl_build.sh ``` -------------------------------- ### Use MKL in LINQPad Source: https://github.com/mathnet/mathnet-numerics/blob/master/docs/MKL.md Explicitly set the native provider path and use the native MKL provider in LINQPad. This method is reliable with or without assembly shadowing. ```csharp Control.NativeProviderPath = @"C:\MKL"; Control.UseNativeMKL(); ``` -------------------------------- ### F# Seed Generation Options Source: https://github.com/mathnet/mathnet-numerics/blob/master/docs/Random.md Demonstrates different methods for generating seeds in F#. The robust seed is recommended for general use. ```fsharp let someTimeSeed = RandomSeed.Time() // not recommended let someGuidSeed = RandomSeed.Guid() let someRobustSeed = RandomSeed.Robust() // recommended, used by default ``` -------------------------------- ### Set Native Provider Path for MKL Source: https://github.com/mathnet/mathnet-numerics/blob/master/docs/MKL.md Set the `NativeProviderPath` to a directory containing MKL binaries. Numerics will automatically select the correct architecture (e.g., x86, x64) based on the running process. ```csharp Control.NativeProviderPath = @"C:\MKL"; ``` -------------------------------- ### Accessing and Setting Matrix Elements (C#) Source: https://github.com/mathnet/mathnet-numerics/blob/master/docs/Matrix.md Demonstrates how to access and modify individual elements of a matrix using indexers. Using the `At` method is slightly faster but bypasses range checks, so use it cautiously after manual validation. ```csharp var m = Matrix.Build.Dense(3,4,(i,j) => 10*i + j); m[0,0]; // 0 (row 0, column 0) m[2,0]; // 20 (row 2, column 0) m[0,2]; // 2 (row 0, column 2) m[0,2] = -1.0; m[0,2]; // -1 ``` -------------------------------- ### F# Mersenne Twister Instance and Module Usage Source: https://github.com/mathnet/mathnet-numerics/blob/master/docs/Random.md Illustrates creating Mersenne Twister instances directly or via the Random module in F#, including options for seeding and thread-safety. ```fsharp // By using the normal constructor (random1 has type MersenneTwister) let random1 = MersenneTwister() let random1b = MersenneTwister(42) // with seed // By using the Random module (random2 has type System.Random) let random2 = Random.mersenneTwister () let random2b = Random.mersenneTwisterSeed 42 // with seed let random2c = Random.mersenneTwisterWith 42 false // opt-out of thread-safety ``` -------------------------------- ### Create Dense Matrix Using Initialization Function Source: https://github.com/mathnet/mathnet-numerics/blob/master/docs/Matrix.md Creates a dense matrix where each element is initialized by a function based on its row and column index. Uses the Matrix builder shortcut. ```csharp M.Dense(3, 4, (i,j) => 100*i + j); ``` -------------------------------- ### Find Real Roots of a Function using RealRoots Source: https://github.com/mathnet/mathnet-numerics/wiki/What's-New Use the RealRoots facade for simple root-finding scenarios. Specify the function, and an interval where a root is expected. Accuracy can be optionally set. ```cs RealRoots.OfFunction(x => x*x - 4, -5, 5) // -2.00000000046908 ``` ```cs RealRoots.OfFunction(x => x*x - 4, -5, 5, accuracy: 1e-14) // -2 (exact) ``` ```cs RealRoots.OfFunctionAndDerivative(x => x*x - 4, x => 2*x, -5, 5) // -2 (exact) ``` -------------------------------- ### Sample from Continuous and Discrete Distributions (F#) Source: https://github.com/mathnet/mathnet-numerics/blob/master/docs/Probability.md Samples random numbers from configured continuous (Normal, Exponential, Gamma) and discrete (Poisson, Geometric) distributions. ```fsharp // sample some random numbers from these distributions // continuous distributions sample to floating-point numbers: let continuous = [ yield normal.Sample() yield exponential.Sample() yield! gamma.Samples() |> Seq.take 10 ] // discrete distributions on the other hand sample to integers: let discrete = [ poisson.Sample() poisson.Sample() geometric.Sample() ] ``` -------------------------------- ### Static Gamma Distribution Functions (C#) Source: https://github.com/mathnet/mathnet-numerics/blob/master/docs/Probability.md Utilize static methods for probability functions and sampling of the Gamma distribution when specific parameters are known. This approach avoids the need to instantiate a distribution object. ```csharp // distribution parameters must be passed as arguments double a2 = Gamma.PDF(2.0, 1.5, 2.3); double randomSample2 = Gamma.Sample(2.0, 1.5); ``` -------------------------------- ### Publish Documentation Source: https://github.com/mathnet/mathnet-numerics/blob/master/docs/Build.md Publishes the generated documentation. This is part of the official release process. ```bash build.sh PublishDocs ``` -------------------------------- ### Accessing Matrix Elements (F#) Source: https://github.com/mathnet/mathnet-numerics/blob/master/docs/Matrix.md Shows how to access a specific element in a matrix using F# indexing syntax. Note the use of `.[ ]` for access. ```fsharp m.[2,0] // 20 ``` -------------------------------- ### Create Random Dense Matrices (Uniform and Gamma Distributions) (F#) Source: https://github.com/mathnet/mathnet-numerics/blob/master/docs/Matrix.md Generates dense matrices with elements drawn from specified continuous distributions (Uniform and Gamma). ```fsharp let m7a = DenseMatrix.random 3 4 (ContinuousUniform(-2.0, 4.0)) let m7b = DenseMatrix.random 3 4 (Gamma(1.0, 2.0)) ``` -------------------------------- ### Import Math.NET Numerics Statistics Namespace Source: https://github.com/mathnet/mathnet-numerics/blob/master/docs/DescriptiveStatistics.md Before using the statistics functionalities, you need to reference the MathNet.Numerics.dll and open the MathNet.Numerics.Statistics namespace. ```csharp using MathNet.Numerics.Statistics; ``` -------------------------------- ### Try Find Root using Brent's Method (F#) Source: https://github.com/mathnet/mathnet-numerics/wiki/What's-New Use the exception-free TryFindRoot method with F# pattern matching to find roots. Returns a boolean indicating success and the root if found. ```fs match Brent.TryFindRoot((fun x -> Evaluate.Polynomial(x, 6., -50., 4., 2.)), -6.5, -5.5, 1.e-8, 100) with | true, root -> sprintf "Root at %f" root | false, _ -> "No root found" ``` -------------------------------- ### Download NuGet Executable Source: https://github.com/mathnet/mathnet-numerics/blob/master/docs/index.md Downloads the nuget.exe executable using curl. This is necessary for managing NuGet packages on Linux. ```sh sudo mozroots --import --sync curl -L https://nuget.org/nuget.exe -o nuget.exe ``` -------------------------------- ### Publish API Documentation Source: https://github.com/mathnet/mathnet-numerics/blob/master/docs/Build.md Publishes the API documentation. This is part of the official release process. ```bash build.sh PublishApi ``` -------------------------------- ### Extracting Row, Column, and Submatrix (C#) Source: https://github.com/mathnet/mathnet-numerics/blob/master/docs/Matrix.md Illustrates how to extract a column vector, a row vector, or a submatrix from an existing matrix. These operations return new matrix or vector instances. ```csharp var m = M.Dense(6,4,(i,j) => 10*i + j); m.Column(2); // [2,12,22,32,42,52] m.Row(3); // [30,31,32,33] m.SubMatrix(1,2,1,2); // [11,12; 21,22] ``` -------------------------------- ### Custom Matrix String Formatting Source: https://github.com/mathnet/mathnet-numerics/blob/master/docs/Matrix.md Demonstrates how to customize the string representation of a matrix using format strings and culture information. This allows for control over floating-point precision and decimal separators. ```text // var m = Matrix.Build.Random(5,100,42); // 42 = random seed // m.ToString() DenseMatrix 5x100-Double 0.408388 -0.847291 -0.320552 0.162242 2.46434 .. 0.180466 -0.278793 -1.06988 0.063008 -0.527378 1.40716 -0.5962 .. -0.622447 -0.488186 -0.734176 -0.703003 1.33158 0.286498 1.44158 .. -0.834335 -0.0756724 1.78532 0.020217 1.94275 -0.742821 -0.790251 .. 1.52823 2.49427 -0.660645 1.28166 -1.71351 -1.33282 -0.328162 .. 0.110989 0.252272 ``` ```text // m.ToString("G2", CultureInfo.GetCultureInfo("de-DE")) DenseMatrix 5x100-Double 0,41 -0,85 -0,32 0,16 2,5 -0,77 0,12 0,58 .. 0,18 -0,28 -1,1 0,063 -0,53 1,4 -0,6 -2,8 -0,35 0,3 .. -0,62 -0,49 -0,73 -0,7 1,3 0,29 1,4 -0,00022 -0,3 0,51 .. -0,83 -0,076 1,8 0,02 1,9 -0,74 -0,79 0,088 0,78 -0,94 .. 1,5 2,5 -0,66 1,3 -1,7 -1,3 -0,33 -0,69 -0,27 -0,68 .. 0,11 0,25 ``` ```text // m.ToString(3,5) // max 3 rows, 5 columns DenseMatrix 5x100-Double 0.408388 -0.847291 -0.320552 .. 0.180466 -0.278793 -1.06988 0.063008 -0.527378 .. -0.622447 -0.488186 -0.734176 -0.703003 1.33158 .. -0.834335 -0.0756724 .. .. .. .. .. .. ``` -------------------------------- ### Custom Matrix String Representation with Delimiters Source: https://github.com/mathnet/mathnet-numerics/blob/master/docs/Matrix.md Illustrates advanced string formatting for matrices using custom delimiters for columns, rows, and sub-matrices. This is useful for creating compact or visually distinct representations. ```text // Matrix.Build.Random(100,100,42) // .ToMatrixString(2,4,3,4,"=","||","\\", " ",Environment.NewLine,x=>x.ToString("G2")) 0.41 0.36 0.29 = 0.43 0.56 -0.56 0.98 -1.1 -0.64 0.9 = 0.49 -0.3 2 -0.5 || || || \ || || || || -0.87 -2.2 0.79 = 0.96 1.8 1.4 0.067 -0.14 -0.016 -0.55 = -0.36 0.33 0.24 0.52 -1.3 -1 -0.81 = 1.3 1 -1.1 -0.28 -0.21 -1.7 2.6 = -1.5 -1.2 -0.0014 3.4 ``` -------------------------------- ### Generate Random Walks (F#) Source: https://github.com/mathnet/mathnet-numerics/blob/master/docs/Probability.md Generates sequences for random walks by accumulating samples from Normal and Cauchy distributions. ```fsharp Seq.scan (+) 0.0 (Normal.Samples(0.0, 1.0)) |> Seq.take 10 |> Seq.toArray Seq.scan (+) 0.0 (Cauchy.Samples(0.0, 1.0)) |> Seq.take 10 |> Seq.toArray ``` -------------------------------- ### Configure DYLD_LIBRARY_PATH on macOS Source: https://github.com/mathnet/mathnet-numerics/blob/master/docs/MKL.md Add paths to the generated MKL libraries in your DYLD_LIBRARY_PATH environment variable by editing your .bash_profile. Replace 'Lionel' with your actual username. ```sh export DYLD_LIBRARY_PATH=$DYLD_LIBRARY_PATH:/Users/Lionel/../mathnet-numerics/out/MKL/OSX/x64 export DYLD_LIBRARY_PATH=$DYLD_LIBRARY_PATH:/Users/Lionel/../mathnet-numerics/out/MKL/OSX/x86 ``` -------------------------------- ### Create Diagonal Identity Matrix with Generic Builder Source: https://github.com/mathnet/mathnet-numerics/wiki/Upgrading-to-Version-3 When frequently using a specific data type like doubles, consider declaring a shorthand for the builder, e.g., `var M = Matrix.Build;`. This simplifies matrix creation. ```csharp M.DiagonalIdentity(4); ``` -------------------------------- ### Calculate Minimum and Maximum using Extension Methods Source: https://github.com/mathnet/mathnet-numerics/blob/master/docs/DescriptiveStatistics.md Use the Minimum() and Maximum() extension methods provided by Math.NET Numerics to find the smallest and largest values in an array of doubles. These methods are directly affected by outliers. ```csharp var samples = new ChiSquare(5).Samples().Take(1000).ToArray(); var largestElement = samples.Maximum(); var smallestElement = samples.Minimum(); ``` -------------------------------- ### Normalize and Solve Linear System in F# Source: https://github.com/mathnet/mathnet-numerics/blob/master/docs/LinearEquations.md Demonstrates normalizing a non-standard linear system into the Ax = b form and then solving it. This involves manipulating the matrix and vector to isolate the unknowns. ```fsharp let A' = matrix [[ 3.0; 4.0; -1.0; 0.0 ] [ 4.0; 5.0; 0.0; -1.0 ] [ 5.0; 6.0; 0.0; 0.0; ] [ 6.0; 7.0; 0.0; 0.0 ]] let b' = vector [ 0.0; 0.0; 20.0; 0.0 ] let x' = A'.Solve(b') // -140; 120; 60; 40 ``` -------------------------------- ### Pack and Store Matrices for Writing Source: https://github.com/mathnet/mathnet-numerics/blob/master/docs/MatlabFiles.md Packs multiple matrices into MatlabMatrix data elements and stores them into a MAT file. Matrix names must not contain spaces. ```csharp var matrices = new List(); m.Add(MatlabWriter.Pack(myFirstMatrix, "m1"); m.Add(MatlabWriter.Pack(mySecondMatrix, "m2"); MatlabWriter.Store("file.mat", matrices); ``` -------------------------------- ### Create Normal Distribution (C#) Source: https://github.com/mathnet/mathnet-numerics/blob/master/docs/Probability.md Instantiates a Normal distribution with specified mean and precision. ```csharp var normal = Normal.WithMeanPrecision(0.0, 0.5); ``` -------------------------------- ### Compile and Run C# Program Source: https://github.com/mathnet/mathnet-numerics/blob/master/docs/index.md Commands to compile a C# file using mcs and then run the compiled executable with mono. ```sh # single line: mcs -optimize -lib:packages/MathNet.Numerics.3.0.0-alpha8/lib/net40/ -r:MathNet.Numerics.dll Start.cs -out:Start # launch: mono Start ``` -------------------------------- ### Find Real Roots using Brent's Method Source: https://github.com/mathnet/mathnet-numerics/wiki/What's-New Directly use Brent's method for root finding, allowing specification of maximum iterations. This method is the default for RealRoots.OfFunction. ```cs Func f = x => Evaluate.Polynomial(x, 6, -50, 4, 2); Brent.FindRoot(f, -6.5, -5.5, 1e-8, 100); // -6.14665621970684 ``` ```cs Brent.FindRoot(f, -0.5, 0.5, 1e-8, 100); // 0.121247371972135 ``` ```cs Brent.FindRoot(f, 3.5, 4.5, 1e-8, 100); // 4.02540884774855 ``` -------------------------------- ### Create Gamma Distribution with Custom Random Generator (C#) Source: https://github.com/mathnet/mathnet-numerics/blob/master/docs/Probability.md Instantiates a Gamma distribution with specified parameters and a custom MersenneTwister random generator. The random generator can be replaced later. ```csharp var gamma2 = new Gamma(2.0, 1.5, new MersenneTwister()); // the random generator can also be replaced on an existing instance gamma2.RandomSource = new Mrg32k3a(); ``` -------------------------------- ### Coercing Small Numbers to Zero (C#) Source: https://github.com/mathnet/mathnet-numerics/blob/master/docs/Matrix.md Demonstrates how to set very small floating-point numbers to zero to handle precision issues. This can be done using a small threshold value or a custom predicate function. ```csharp m.CoerceZero(1e-14); // set all elements smaller than 1e-14 to 0 m.CoerceZero(x => x < 10); // set all elements that match a predicate function to 0. ``` -------------------------------- ### Watch and Regenerate Documentation Locally Source: https://github.com/mathnet/mathnet-numerics/blob/master/docs/Build.md Monitor documentation content files and automatically regenerate HTML output incrementally. This is useful for local editing and previewing. ```bash ./build.sh DocsWatch ``` -------------------------------- ### Restore NuGet Packages with Paket Source: https://github.com/mathnet/mathnet-numerics/blob/master/docs/Build.md Restore NuGet packages to the exact version specified in the 'paket.lock' file using the Paket CLI. ```bash .paket/paket.exe restore ``` -------------------------------- ### Matrix Row/Column Removal and Concatenation (C#) Source: https://github.com/mathnet/mathnet-numerics/blob/master/docs/Matrix.md Illustrates operations that create new matrices by removing rows or columns, or by stacking/appending existing matrices. These operations do not modify the original matrices. ```csharp var m2 = m.RemoveRow(2); // remove the 3rd rows var m3 = m2.RemoveColumn(3); // remove the 4th column var m4 = m.Stack(m2); // new matrix with m on top and m2 on the bottom var m5 = m2.Append(m3); // new matrix with m2 on the left and m3 on the right var m6 = m.DiagonalStack(m3); // m on the top left and m3 on the bottom right ``` -------------------------------- ### C# Mersenne Twister Instance Usage Source: https://github.com/mathnet/mathnet-numerics/blob/master/docs/Random.md Demonstrates typical usage of the Mersenne Twister generator with an instance in C#, including seeding and generating various types of random numbers. ```csharp // Typical way with an instance: var random = new MersenneTwister(42); // seed 42 int sampleInt = random.Next(); double sampleDouble = random.NextDouble(); decimal sampleDecimal = random.NextDecimal(); double[] samples = random.NextDoubles(1000); IEnumerable sampleSeq = random.NextDoubleSequence(); ``` -------------------------------- ### Initialize DescriptiveStatistics Class Source: https://github.com/mathnet/mathnet-numerics/blob/master/docs/DescriptiveStatistics.md Instantiate the DescriptiveStatistics class with a collection of samples to compute various statistical measures in one pass. This class is useful for gathering a whole set of statistical characteristics efficiently. ```csharp var samples = new ChiSquare(5).Samples().Take(1000); var statistics = new DescriptiveStatistics(samples); var largestElement = statistics.Maximum; var smallestElement = statistics.Minimum; var median = statistics.Median; var mean = statistics.Mean; var variance = statistics.Variance; var stdDev = statistics.StandardDeviation; var kurtosis = statistics.Kurtosis; var skewness = statistics.Skewness; ``` -------------------------------- ### ToString for a 3x4 Dense Matrix Source: https://github.com/mathnet/mathnet-numerics/blob/master/docs/Matrix.md Demonstrates the string representation of a small dense matrix, showing all elements. ```text // Matrix.Build.Dense(3,4,(i,j) => i*10*j).ToString() DenseMatrix 3x4-Double 0 0 0 0 0 10 20 30 0 20 40 60 ``` -------------------------------- ### Fourier Transforms (DFT/FFT) Source: https://github.com/mathnet/mathnet-numerics/blob/master/docs/IntegralTransforms.md Provides implementations for various Discrete Fourier Transform (DFT) algorithms, including Naive DFT, Radix-2 FFT, and Bluestein FFT. The Transform class offers convenient static methods for forward and inverse Fourier transforms. ```APIDOC ## Fourier Space: Discrete Fourier Transform and FFT Provides implementations of the following algorithms: * *Naive Discrete Fourier Transform (DFT):* Out-place transform for arbitrary vector lengths. Mainly intended for verifying faster algorithms: _[NaiveForward](https://numerics.mathdotnet.com/api/MathNet.Numerics.IntegralTransforms/Fourier.htm#NaiveForward)_, _[NaiveInverse](https://numerics.mathdotnet.com/api/MathNet.Numerics.IntegralTransforms/Fourier.htm#NaiveInverse)_ * *Radix-2 Fast Fourier Transform (FFT):* In-place fast Fourier transform for vectors with a power-of-two length (Radix-2): _[Radix2Forward](https://numerics.mathdotnet.com/api/MathNet.Numerics.IntegralTransforms/Fourier.htm#Radix2Forward)_, _[url:Radix2Inverse](https://numerics.mathdotnet.com/api/MathNet.Numerics.IntegralTransforms/Fourier.htm#Radix2Inverse)_ * *Bluestein Fast Fourier Transform (FFT):* In-place fast Fourier transform for arbitrary vector lengths: _[BluesteinForward](https://numerics.mathdotnet.com/api/MathNet.Numerics.IntegralTransforms/Fourier.htm#BluesteinForward)_, _[url:BluesteinInverse](https://numerics.mathdotnet.com/api/MathNet.Numerics.IntegralTransforms/Fourier.htm#BluesteinInverse)_ Furthermore, the _[Transform](https://numerics.mathdotnet.com/api/MathNet.Numerics.IntegralTransforms/Transform.htm)_ class provides a shortcut for the Bluestein FFT using static methods which are even easier to use: _[FourierForward](https://numerics.mathdotnet.com/api/MathNet.Numerics.IntegralTransforms/Transform.htm#FourierForward)_, _[FourierInverse](https://numerics.mathdotnet.com/api/MathNet.Numerics.IntegralTransforms/Transform.htm#FourierInverse)_. ### Code Sample using the Transform class: ```csharp // create a complex sample vector of length 96 Complex[] samples = SignalGenerator.EquidistantInterval( t => new Complex(1.0 / (t * t + 1.0), t / (t * t + 1.0)), -16, 16, 96); // inplace bluestein FFT with default options Transform.FourierForward(samples); ``` ### Fourier Options: * *Default:* Uses a negative exponent sign in forward transformations, and symmetric scaling (that is, sqrt(1/N) for both forward and inverse transformation). This is the convention used in Maple and is widely accepted in the educational sector (due to the symmetry). * *AsymmetricScaling:* Set this flag to suppress scaling on the forward transformation but scale the inverse transform with 1/N. * *NoScaling:* Set this flag to suppress scaling for both forward and inverse transformation. Note that in this case if you apply first the forward and then inverse transformation you won't get back the original signal (by factor N/2). * *InverseExponent:* Uses the positive instead of the negative sign in the forward exponent, and the negative (instead of positive) exponent in the inverse transformation. * *Matlab:* Use this flag if you need MATLAB compatibility. Equals to setting the _AsymmetricScaling_ flag. This matches the definition used in the [url:wikipedia article|https://en.wikipedia.org/wiki/Discrete_Fourier_transform]. * *NumericalRecipes:* Use this flag if you need Numerical Recipes compatibility. Equal to setting both the _InverseExponent_ and the _NoScaling_ flags. ### Useful symmetries of the Fourier transform: * h(t) is real valued <=> real part of H(f) is even, imaginary part of H(f) is odd * h(t) is imaginary valued <=> real part of H(f) is odd, imaginary part of H(f) is even * h(t) is even <=> H(f) is even * h(t) is odd <=> H(f) is odd * h(t) is real-valued even <=> H(f) is real-valued even * h(t) is real-valued odd <=> H(f) is imaginary-valued odd * h(t) is imaginary-valued even <=> H(f) is imaginary-valued even * h(t) is imaginary-valued odd <=> H(f) is real-valued odd ``` -------------------------------- ### Publish NuGet Packages Source: https://github.com/mathnet/mathnet-numerics/blob/master/docs/Build.md Publishes the generated NuGet packages. This is the final step in the official release process. ```bash build.sh PublishNuGet ``` -------------------------------- ### Load F# Packages and Compute Gamma Function Source: https://github.com/mathnet/mathnet-numerics/blob/master/docs/index.md Loads Math.NET Numerics F# extensions and computes the Gamma function for 0.5. This is useful for interactive F# sessions. ```fsharp #load "../packages/MathNet.Numerics.FSharp/MathNet.Numerics.fsx" open MathNet.Numerics SpecialFunctions.Gamma(0.5) ``` -------------------------------- ### Copy MKL Libraries to /usr/lib on Linux Source: https://github.com/mathnet/mathnet-numerics/blob/master/docs/MKL.md Copy the MKL native libraries to /usr/lib for system-wide access on Linux. This requires root privileges. ```sh sudo cp packages/MathNet.Numerics.MKL.Linux-x64.1.3.0/content/libiomp5.so /usr/lib/ sudo cp packages/MathNet.Numerics.MKL.Linux-x64.1.3.0/content/libMathNetNumericsMKL.dll /usr/lib/ ``` -------------------------------- ### Create Random Dense Matrix (Standard Distribution) (F#) Source: https://github.com/mathnet/mathnet-numerics/blob/master/docs/Matrix.md Generates a dense matrix with elements drawn from a standard normal distribution. ```fsharp let m6 = DenseMatrix.randomStandard 3 4 ``` -------------------------------- ### Create Dense Random Matrix from Distribution Source: https://github.com/mathnet/mathnet-numerics/blob/master/docs/Matrix.md Creates a dense matrix filled with random numbers sampled from a specified distribution (e.g., Gamma). Requires importing MathNet.Numerics.Distributions. ```csharp M.Random(3, 4, new Gamma(1.0, 5.0)); ``` -------------------------------- ### Map Function Over Array (F#) Source: https://github.com/mathnet/mathnet-numerics/blob/master/docs/Generate.md Demonstrates mapping a function over an array in F# using the standard Array module. This is the idiomatic F# approach for such operations. ```fsharp Array.map ((+) 1.0) a ``` -------------------------------- ### Create Dense Matrix from Column Arrays (C#) Source: https://github.com/mathnet/mathnet-numerics/blob/master/docs/Matrix.md Initializes a dense matrix using a params-array of arrays, where each inner array represents a column. ```csharp M.DenseOfColumnArrays(new[] {2.0, 3.0}, new[] {4.0, 5.0}); ``` -------------------------------- ### Create Dense Matrix Initialized by Function (F#) Source: https://github.com/mathnet/mathnet-numerics/blob/master/docs/Matrix.md Initializes a dense matrix where each element is computed by a function based on its row and column indices. ```fsharp let m3 = DenseMatrix.init 3 4 (fun i j -> float (i+j)) ``` -------------------------------- ### Find Polynomial Roots using Bisection Method in Visual Basic Source: https://github.com/mathnet/mathnet-numerics/blob/master/docs/index.md Finds the roots of the quadratic equation 2x^2 - 2x - 2 = 0 using the Bisection method in Visual Basic. Requires the MathNet.Numerics.RootFinding namespace. ```visualbasic Imports MathNet.Numerics.RootFinding Dim f As Func(Of Double, Double) = Function(x) 2*x^2 - 2*x - 2 Bisection.FindRoot(f, 0, 2) ' returns 1.61803398874989 Bisection.FindRoot(f, -2, 0) ' returns -0.618033988749895 ``` -------------------------------- ### Matrix Arithmetic Operators (F#) Source: https://github.com/mathnet/mathnet-numerics/blob/master/docs/Matrix.md Demonstrates common arithmetic operations between matrices, vectors, and scalars using operator overloading. ```fsharp let m = matrix [[ 1.0; 4.0; 7.0 ] [ 2.0; 5.0; 8.0 ] [ 3.0; 6.0; 9.0 ]] let v = vector [ 10.0; 20.0; 30.0 ] let v' = m * v let m' = m + 2.0*m ``` -------------------------------- ### Map Function with Two Inputs (LINQ) Source: https://github.com/mathnet/mathnet-numerics/blob/master/docs/Generate.md Demonstrates mapping a function with two inputs over two arrays in C# using LINQ's `Zip` method. The result is then converted back to an array. ```csharp a.Zip(b, (x, y) => x + y).ToArray(); ``` -------------------------------- ### Restore Dependencies Source: https://github.com/mathnet/mathnet-numerics/blob/master/docs/Build.md Restore project dependencies before building or using an IDE. Run this command after every git checkout. ```bash restore.cmd # or ./restore.sh ```