Click here to Skip to main content
6,595,854 members and growing! (18,398 online)
Email Password   helpLost your password?
Languages » C# » General     Intermediate

C# Matrix Library

By hanzzoid

A C# library for basic numerical linear algebra.
C# 2.0, Windows, .NET 2.0VS2005, Dev, QA
Posted:2 Jun 2007
Updated:28 Nov 2007
Views:56,270
Bookmarked:46 times
Unedited contribution
Announcements
Loading...
 
Search    
Advanced Search
Add to IE Search
printPrint   add Share
      Discuss Discuss   Broken Article?Report  
21 votes for this article.
Popularity: 3.94 Rating: 2.98 out of 5
4 votes, 19.0%
1

2
4 votes, 19.0%
3
5 votes, 23.8%
4
8 votes, 38.1%
5

Download csml_complex.zip - 167.3 KB

Download doc.zip - 210.8 KB (Documentation)

Version Info

Version 0.9 - Last Update: July 4, 2007

Introduction

CSML - C# Matrix Library - is a compact and lightweight package for numerical linear algebra. Many matrix operations known from Matlab, Scilab and Co. are implemented.

Remark

Make sure to return to this article once in a while for updates. A project of this size a is big thing for one man to handle. Scilab (free Matlab clone), for instance, has been created by an academic consortium, and Matlab's creator, Mathworks, is a well-fed enterprise.

Bugfixes will always come as updates, and if you have a look at the history below, you will see there have been quit a number of, ehm, improvements in a short period of time.

What it can do

The core of the library, the Matrix class, includes over 90 methods for matrix operations such as multiplication, summation, exponentiation and solving linear equation systems; matrix manipulations such as concatenation, insertion, transpose, inverse, flipping, symmetrizing, insertion and extraction; for matrix computations such as determinant, trace, permanent, norm (Frobenius, Euclidian, maximum norm, taxi norm, p-norm), condition number; for matrix decompositions such as LU factorization, Gram-Schmidtian orthogonalization and Cholesky factorization.

Now, the entire library has been updated to work with complex arithmetics. A real matrix M is to be considered a special complex matrix, where M.Re() == M, e.i. imaginary part of each entry equals 0.

The project is nearly entirely pdf-documented; most methods are also illustrated with examples. Difficult algorithms like the computation of the inverse are explained on a mathematical level as well. If vitally necessary, complexity classes of certain algrithms are noted.

What it cannot do

At this time, there is no implementation of

  • polynomials, interpolation, integration (*);
  • eigenvectors (*);

(*) - Working on it. Any contribution is welcome. A complex numbers library has been issued by me here on CodeProject, look for CompLib. A library for polynomials is has been released as well, PolyLib.

How to use CSML

Two general possibilities for using the code:

  1. Include CSML.dll as reference to your project and type "using CSML;" on top of your source file
  2. Include classes Matrix.cs and Complex.cs to your project and adjust namespaces

Let us see an example. Say, we want to compute the determinant and the inverse of the 2 by 2 matrix [1, 1; 1, 2]:

Matrix M = new Matrix("1,1;1,2"); // init

Complex det = M.Determinant(); // det = 1
Matrix Minv = M.Inverse(); // Minv = [2, -1; -1, 1]

For details of implementation and usage, refer to the documentation.

Points of Interest

This project is issued without license and warranty, it should be considered a gift to the developer's community in general and to this page in particular - most of my programming knowledge is based on free code, on examples and tutorials submitted without the greed for money. I am now in the happy position not having to turn anything into bucks: This is the result.

A Word About Eigenvalues

The Eigenvalues() method in its current state uses basic QR iteration based upon Gram-Schmidtian orthogonalization. This implies two things:

  1. for now, computation of eigenvalues is possible only for real matrices
  2. if a matrix has multiple eigenvalues or complex eigenvalues, the method works, but junk may be returned

In fact, I had thoroughly satifying results only for triangular matrices and symmetric positive definite matrices.

These problems mirror the difficulties buried under the eigenvalue problem. Since the eigenvalues of a matrix A are defined as the roots of the characteristic polynomial

p(L) = det(A-L*id),

computation is mathematically equivalent to the computation of a determinant and the n roots of p. (Well, this would work for all matrices with any distribution of eigenvalues, but it is numerically the worst idea, since Weierstrass iteration (compare the Roots() method in PolyLib) is badly conditioned for polynomials with roots not being well-separated.)

Therefore; I am working on canonical double-shift QR iteration based upon Givens rotations. That is the way Matlab's function eig is working.

That I am forced to talk at length about eigenvalues, although there are so many other difficult computations implemented, reveals to me that this problem is one of the deepest and most bothersome in basic numerical linear algebra.

History

Coming soon

  • conjugate gradient method (SolveCG() is implemented but buggy); I'm going to issue an example project showing usage and basic functionality of CSML one of these days

Update July 4, 2007

  • added Hessenberg-Householder reduction, Householder reflection and Givens rotation; HessenbergHouseholder() works nicely; QRGivens() and QRIterationHessenberg() are still buggy
  • slightly modified constructors for vector initialization
  • bug in InverseLeverrier() fixed; this black box method should now be standard for matrix inversion (Inverse() is much slower for general matrices, but fast for special matrices being orthogonal, unitary or diagonal)
  • ToString(string format) method in Complex.cs beautified; Multiplication of double and complex values slightly changed (no bugs there, but inconsistencies)

Update July 3, 2007 #2

  • major bug in Arg() fixed (thanks Petr Stanislav!); this affected Log(), Pow() and Sqrt()

Update July 3, 2007

  • (1) minor bug within the matrix access routine fixed, making two try-catch blocks obsolete and increasing speed enormously; (2) defined matrix exponentiation with negative exponent k as exponentiation of the inverse with (-k); (3) major bug within the Insert() method fixed; (4) old matrix class (without complex number support) deleted

Update July 2, 2007

  • A rainy Monday in Bavaria... Instead of learning for my exams, I updated and finished the documentation and added the hyperbolic functions Sinh, Cosh, Tanh, Coth, Sech, Csch to the Complex class.
  • SolveSafe fixed, renamed to Solve and made static. This method is now nearly equivalent to the Matlab backslash operator. Fixation of SolveSafe (using LU decomposition with column pivoting) suddenly made the old Solve method superfluous, which has been removed.
  • method Size removed and replaced with read-only properties RowCount and ColumnCount
  • method IsVector renamed with VectorLength (tests, if a matrix is a vector, e.i. n by 1 or 1 by n)

Update June 29, 2007

  • Finally complex numbers and complex matrices; any matrix consists of complex entries now.

    New in this version:

    • major bug in IsPermutation() removed (now: permutation matrices are precisely the involutary 0-1 matrices; refer to doc)
    • tests for complex matrices implemented: IsUnitary(), IsReal(), IsImaginary(), IsHermitian()
    • test added: IsZeroOneMatrix()
    • KroneckerDelta() implemented
    • Gram-Schmidtian orthogonalization
    • QR iteration based on Gram-Schmidt
    • function for eigenvalues (slow!)
    • general method Insert() to insert a submatrix at a certain position
    • general method Extract() to copy a submatrix from a given matrix
    • Conjugate(), ConjugateTranpose()
    • BlockMatrix() to build a matrix from four given matrices
    • ChessboardMatrix() to construct matrices with interchanging 0-1 entries
    • RandomZeroOne()
    • Random() extended to generate not just double, but also integer matrices
    • Re(), Im() to extract the real/imaginary parts of a matrix
    • SolveSafe() marked as buggy
    • Eigenvector(), SolveCG(), QRHessenbergHouseholder(), HouseholderVector() implemented but yet (correctly) marked as buggy
    • documentation updated (but not finished)
    • faster method for matrix inversion: InverseLeverrier(), using the Leverrier method (rtfm)

Update June 10, 2007

  • major multiplication bug removed; in "Matrix operator *(Matrix A, double x)"
  • test for definiteness added (works for symmetric matrices only); needs beta-testing!
  • test for symmetric positive definiteness (SPD) added and used within Cholesky(); Cholesky decomposition is possible only for SPD matrices
  • undocumented basic graph algorithms: BFS (broad-first search), DFS (depth-first search) and Floyd (shortest paths between all vertices of a graph)

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here

About the Author

hanzzoid


Member

Location: Germany Germany

Other popular C# articles:

Article Top
You must Sign In to use this message board.
FAQ FAQ 
 
Noise Tolerance  Layout  Per page   
 Msgs 1 to 25 of 43 (Total in Forum: 43) (Refresh)FirstPrevNext
GeneralLatest developments Pinmembercornelius17298:04 29 Oct '09  
GeneralBug in Matrix Inverse PinmemberRajnikant Sharma BYU6:35 17 May '09  
GeneralRe: Bug in Matrix Inverse Pinmembersafee ullah18:32 2 Sep '09  
General3 warrnings detected Pinmemberchen dingjun13:15 17 Dec '08  
GeneralHorizontalConcat seems to have a bug PinmemberMatthias Zeintlinger6:50 3 Dec '08  
GeneralRe: HorizontalConcat seems to have a bug PinmemberHåkan MacLean6:56 5 Apr '09  
Generalbug in Inverse()-Method Pinmemberarthur_dent427:35 8 Apr '08  
GeneralInverse Matrix of Array Pinmemberget2:45 13 Dec '07  
Questionstrange operator consequences? PinmemberRaven1236:00 27 Nov '07  
AnswerRe: strange operator consequences? Pinmemberhanzzoid0:05 29 Nov '07  
GeneralGreat Pinmemberzhengdong jin5:18 23 Nov '07  
GeneralRe: Great PinmemberRajnikant Sharma BYU15:56 28 Dec '08  
GeneralHorizontalConcat() and VerticalConcat() do not work Pinmemberalexei_c14:51 21 Oct '07  
GeneralRe: HorizontalConcat() and VerticalConcat() do not work Pinmemberhanzzoid0:24 29 Nov '07  
QuestionInverse of m x n matrix? Pinmemberjoselvra13:56 29 Sep '07  
AnswerRe: Inverse of m x n matrix? Pinmembermvasiliev22:42 18 Oct '07  
AnswerRe: Inverse of m x n matrix? Pinmemberhanzzoid0:09 29 Nov '07  
Generalexception thrown Pinmemberslady.net18:05 28 Aug '07  
Generaloperations Pinmembermatiasjaure4:55 28 Aug '07  
Generalconversion from int to complex PinmemberDrullie195:53 20 Aug '07  
GeneralRe: conversion from int to complex Pinmembercornelius17297:14 29 Oct '09  
GeneralXML comments missing Pinmemberdoolyo23:12 9 Jul '07  
GeneralRe: XML comments missing Pinmemberhanzzoid7:53 14 Jul '07  
GeneralRe: XML comments missing Pinmemberdoolyo14:49 14 Jul '07  
GeneralRe: XML comments missing Pinmembersquid3149:20 16 Jul '07  

General General    News News    Question Question    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

PermaLink | Privacy | Terms of Use
Last Updated: 28 Nov 2007
Editor:
Copyright 2007 by hanzzoid
Everything else Copyright © CodeProject, 1999-2009
Web21 | Advertise on the Code Project