Solve Linear System Example (C#)
[C#]
/* COPYRIGHT(C), SIMPLEXAR SOFTWARE LIMITED, 2006-2008.
* All rights reserved.
*
* Use of this copyright notice is precautionary only, and does not imply
* publication or disclosure. The content of this work contains confidential
* and proprietary information of Simplexar Software Limited. Any duplication,
* modification, distribution, or disclosure in any form, in whole, or in part,
* is strictly prohibited without express prior written permission.
*/
// Get namespaces.
using System;
using Simplexar.Statsar;
using Simplexar.Statsar.LinearAlgebra;
// Start namespace.
namespace Simplexar.Examples.Statsar
{
/// <summary>
/// This example illustrates how to solve a linear system of equations
/// by using the matrix class Solve method.
/// </summary>
public static class Example
{
/// <summary>
/// The application entry point.
/// </summary>
public static void Main()
{
try
{
RunExample();
}
catch(Exception exception)
{
Console.WriteLine(exception);
}
Console.WriteLine("Press ENTER to terminate.");
Console.ReadLine();
}
private static void RunExample()
{
// To illustrate how to solve a linear system of equations,
// consider the linear system below:
//
// 2.5 * x + 3.5 * y + 4.5 * z = 45.5
// 1.5 * x + 2.8 * y + 6.2 * z = 53.48
// 8.2 * x - 1.5 * y + 3 * z = 25.14
//
// To solve this system, we first define a matrix of
// coefficients, and a vector corresponding to the right
// hand side of the linear system. We then use the matrix
// class Solve() method. This method accepts a vector and
// returns a vector. The resulting vector holds the solution
// to the linear system.
Matrix m = new double[,]{
{ 2.5, 3.5, 4.5 },
{ 1.5, 2.8, 6.2 },
{ 8.2, -1.5, 3 }};
Vector v1 = new Vector(45.5, 53.48, 25.14);
Vector v2 = m.Solve(v1);
double x = v2[0];
double y = v2[1];
double z = v2[2];
Console.WriteLine("x = {0}", x);
Console.WriteLine("y = {0}", y);
Console.WriteLine("z = {0}", z);
}
}
}