Click here to Skip to main content
11,584,208 members (43,644 online)
Click here to Skip to main content

A matrix class with serialization and advanced input/output functions

, 12 Aug 2002 CPOL 247.3K 3.3K 66
Rate this:
Please Sign up or sign in to vote.
A Matrix class derived from CObject with serialization and operator overloading

Overview

Matrices, do you hate them? I do, and they turn up all over the place in the projects I work with. So over time I have developed a class CMatrix to handle all the things we need, and some I expect to need in the future.

How the data is handled

First lets take an overview of how the class handles the data. The matrix data is allocated in a flat array of doubles with an integer reference counter at the end of the array. As the matrix is dynamic, we use a reference count system to avoid efficiency hits when assigning/copying one matrix into another. Two object can point to the same data, and they only diverge when one of them changes the data, getting its own copy of the data at that point. The data is only deleted when the last reference to it is being deleted. This has advantages for objects returned by function calls by value, and which are assigned by operator=, as there is little penalty in assigning a pointer compared to a new/copy operation.

Serialization

The CMatrix class inherits directly from CObject and is full serialization compatible.

CMatrixHelper

A small helper class has been added to allow a simulated CMatrix::operator[][] to work. I stole this idea shamelessly from Alex Chirokov's article 2D Matrix Container with [][] indexing. A nice way of doing it. Note also that you should not be creating any objects of this type in your own code. It is used for this purpose only.

Robustness

In DEBUG mode, the code compiles with 0 warnings/errors and has extensive ASSERTion checking through out, so it should catch any problems that you have (or I have) in code. Most of the functionality has been thoroughly checked, but I would recommend checking your results, just in case!

Constructors

You can construct a matrix object using the following methods:

  • CMatrix() Constructs a 1 * 1 array, this is the default constructor.
  • CMatrix(CMatrix& other) Copy constructor
  • CMatrix(nCols, nRows) Constructs a matrix of nCols * nRows dimensions. All data is 0.
  • CMatrix(size, diagonal) Constructs a square matrix with or without 1's on the diagonal.
  • CMatrix(VARIANT) Constructs a CMatrix object from a 2 dimension SAFEFARRAY variant.

As a note, any non-initialized matrix elements will be set to 0 on construction.

Operators overloaded

The following operators have been overloaded:

  • operator=(CMatrix) For standard assignment.

Arithmatic

  • operator+(CMatrix) Adds 2 matrices together, must be the same size
  • operator-(CMatrix) Subtracts 1 matrix from another, must be the same size
  • operator*(CMatrix) Multiples 2 matrices together, the two inner dimensions must be the same, e.g. 3*2 by 2*3
  • operator+=(CMatrix) Adds one matrix onto the current matrix, must have same dimensions.
  • operator-=(CMatrix) Subtracts one matrix from the current matrix, must have same dimensions.
  • operator*=(CMatrix) Mutiples the current matrix by the other matrix
  • operator*=(double) Multiples all matrix elements by the given value
  • operator*(CMatrix, double) Multiples all elements by the given value, returning a new matrix

Comparison

  • operator==(CMatrix) For matrix comparison, returns true if identical, false otherwise.

Element access

  • operator[](int) Works with the class CMatrixHelper to simulate a operator[][].

Get/Set functions

Two standard access function are provided.:

  • GetElement(nCol, nRow) returns the given element value
  • SetElement(nCol, nRow, value) Sets the given element to a different value

Other matrix functions

  • GetNumColumns() Returns the matrices columns dimension
  • GetNumRows() Returns the matrices rows dimension
  • SumColumn(column) Returns the sum of all elements in the given column
  • SumRow(row) Returns the sum of all elements in the given row
  • SumColumnSquared(column) Same as SumColumn() but the return value is squared
  • SumRowSquared(row) Same as SumRow() but the return value is squared
  • GetNumericRange(min, max) Returns the lower and upper values of elements in the matrix
  • GetSafeArray() Returns a VARIANT with a copy of the CMatrix data in a SAFEARRAY. Note that the VARIANT should be cleared using VariantClear(var) unless you pass the VARIANT to a different program (e.g. a COM component/VB) as it becomes their responsibility.
  • CopyToClipboard() Places the CMatrix data in the clipboard as CSV text, use this when debugging etc
  • WriteAsCSVFile(filename) Writes the matrix to a CSV file
  • ReadFromCSVFile(const CString& filename) Creates a new matrix from a CSV file.
  • Dump() TRACEs the matrix content to the debug stream
  • AssertValid() ASSERTs if the object is in an invalid state

Transposition

  • GetTransposed() Returns a new matrix which is a Transpose of the one called on
  • Transpose() Transposes the current matrix

Inversion

  • GetInverted() Returns the inversion of the current matrix
  • Invert() Inverts the current matrix

Covariant (A' * A)

  • Covariant() Returns the Covariant of the current matrix

Normalisation

  • GetNormalised(min, max) Returns the matrix with all values scaled between min and max
  • Normalise(min, max) Normalizes all values in the matrix between min and max

Concatenation

  • GetConcatinatedColumns(CMatrix) Returns a new matrix with the other matrix added onto the right hand side
  • ConcatinateColumns(CMatrix) Concatenates the additional columns onto the current matrix
  • GetConcatenatedRows(CMatrix) Returns a new matrix with the other matrix added onto the bottom of the current matrix
  • ConcatinateRows(CMatrix) Concatenates the additional rows onto the current matrix
  • AddColumn(double*) Adds a new column onto the current matrix
  • AddRow(double*) Adds a new row onto the current matrix

Extraction/substitution

  • ExtractSubMatrix(x, y, x_size, y_size) Extract a sub matrix from a larger matrix
  • SetSubMatrix(x, y, CMatrix) Substitutes a larger matrices elements with those from another matrix
  • ExtractDiagonal() Returns a x * 1 matrix with the values from the diagonal - square matrices only
  • GetSquareMatrix() Returns a square matrix of the smaller dimension, by stepping over rows/columns to make the matrix square
  • MakeSquare() Squares the current matrix by stepping over rows/columns

Other notes

All the code to handle the allocation/deallocation of matrix data and the reference counting is not covered here in the class interface as they are all private functions. You can see the documentation in the source code comments. (wow comments....Big Grin | :-D )

If you find any bugs or have some enhancements for the class, I would be happy if you would pass them along, and I will endeavour to keep the class fully up to date here.

Updates

13th August 2002

  • A small problem with CMatrixHelper when using operator[][] for element read access was fixed by making the return object const.
  • An invalid ASSERTion error in ExtractSubMatrix was fixed.
  • The operator= for CMatrixHelper now copies all member variables across into the target object.

2nd July 2002

  • A small typo in CMatrix::Invert() was fixed. Thanks to Jamie Plowman for spotting it.
  • As suggested, I made the class CMatrixHelper constructors protected and made CMatrix a friend so that only CMatrix can construct objects, not a user.

Enjoy!

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

Share

About the Author

Roger Allen
Software Developer (Senior) Sirius Analytical Instruments
United Kingdom United Kingdom
A research and development programmer working for a pharmaceutical instrument company for the past 17 years.

I am one of those lucky people who enjoys his work and spends more time than he should either doing work or reseaching new stuff. I can also be found on playing DDO on the Cannith server (Send a tell to "Maetrim" who is my current main)

I am also a keep fit fanatic, doing cross country running and am seriously into [url]http://www.ryushinkan.co.uk/[/url] Karate at this time of my life, training from 4-6 times a week and recently achieved my 1st Dan after 6 years.

You may also be interested in...

Comments and Discussions

 
GeneralMy vote of 3 Pin
Mic8-Aug-13 13:27
memberMic8-Aug-13 13:27 
GeneralConverted to MSVC10 Pin
Patrik Kallback19-Nov-10 5:51
memberPatrik Kallback19-Nov-10 5:51 
GeneralRe: Converted to MSVC10 Pin
kiddo35428-Nov-10 6:50
memberkiddo35428-Nov-10 6:50 
GeneralRe: Converted to MSVC10 Pin
Patrik Kallback3-Aug-12 2:34
memberPatrik Kallback3-Aug-12 2:34 
Questioncompile error Pin
MaryamR22-Apr-09 1:03
memberMaryamR22-Apr-09 1:03 
Generalhelp me Pin
cooljeff31-Mar-08 20:45
membercooljeff31-Mar-08 20:45 
Generalhi Pin
sujithkumarsl4-Jun-07 20:36
membersujithkumarsl4-Jun-07 20:36 
GeneralA better version of serialization Pin
cristitomi14-Feb-07 23:56
membercristitomi14-Feb-07 23:56 
QuestionHow to use this class in Visual C++ 6.0 Pin
cristitomi14-Feb-07 5:32
membercristitomi14-Feb-07 5:32 
AnswerRe: How to use this class in Visual C++ 6.0 Pin
whynot12345631-Oct-09 20:54
memberwhynot12345631-Oct-09 20:54 
GeneralQuite slow for 8x8 inverse. Pin
chueh821-Sep-06 8:08
memberchueh821-Sep-06 8:08 
GeneralRe: Quite slow for 8x8 inverse. Pin
alin418712-Sep-11 15:21
memberalin418712-Sep-11 15:21 
GeneralEliminating the helper class Pin
cwbenson14-Jul-06 4:15
membercwbenson14-Jul-06 4:15 
Generallink errors Pin
cwbenson14-Jul-06 3:44
membercwbenson14-Jul-06 3:44 
GeneralError with creating CMatrix objects Pin
kimyuan819-Mar-06 22:39
memberkimyuan819-Mar-06 22:39 
Generalsomebody help! Pin
gampalu14-Feb-06 4:41
membergampalu14-Feb-06 4:41 
GeneralRe: somebody help! Pin
piaoxuecode10-Sep-12 21:04
memberpiaoxuecode10-Sep-12 21:04 
JokeJokes Pin
wepy8888-Dec-05 19:09
memberwepy8888-Dec-05 19:09 
GeneralI need introduce the values in matrix Pin
rubenss18-Oct-05 6:06
memberrubenss18-Oct-05 6:06 
GeneralRe: I need introduce the values in matrix Pin
victorsimon8-Jun-13 5:37
membervictorsimon8-Jun-13 5:37 
Generalsome thing is wrong Pin
chen100013-Oct-05 5:17
memberchen100013-Oct-05 5:17 
Generalto build cmatric Pin
zairee6-Sep-05 22:17
memberzairee6-Sep-05 22:17 
Generalhelp..#include "stdafx.h" Pin
mohamed radwan21-Jun-05 21:21
membermohamed radwan21-Jun-05 21:21 
GeneralComplile Error Pin
terrenzhong6-Jan-05 1:14
memberterrenzhong6-Jan-05 1:14 
GeneralRe: Complile Error Pin
phanduchuynh6-Jan-05 16:19
memberphanduchuynh6-Jan-05 16:19 
GeneralProblem in compiling... plz help Pin
Nagarajan S.31-Aug-04 7:46
memberNagarajan S.31-Aug-04 7:46 
GeneralRe: Problem in compiling... plz help Pin
Nagarajan S.31-Aug-04 8:20
memberNagarajan S.31-Aug-04 8:20 
Questionoperator* fix? Pin
Jonny Gould12-Jul-04 22:58
memberJonny Gould12-Jul-04 22:58 
AnswerRe: operator* fix? Pin
Jonny Gould13-Jul-04 17:46
memberJonny Gould13-Jul-04 17:46 
GeneralRe: operator* fix? Pin
Bill Lim7-Nov-04 21:02
memberBill Lim7-Nov-04 21:02 
Generalcan't compile source Pin
milan0824-Mar-04 17:13
membermilan0824-Mar-04 17:13 
GeneralRow Reduction, Gaussian elimination, row echelon form, matrix inverse Pin
James Reilly6-Feb-04 16:17
memberJames Reilly6-Feb-04 16:17 
QuestionHelp ~! errors in the provided source codes? Pin
Vincent Sim3-Feb-04 5:54
memberVincent Sim3-Feb-04 5:54 
AnswerRe: Help ~! errors in the provided source codes? Pin
James Reilly6-Feb-04 17:28
memberJames Reilly6-Feb-04 17:28 
GeneralRe: Help ~! errors in the provided source codes? Pin
D-bo10-Feb-04 6:58
memberD-bo10-Feb-04 6:58 
GeneralMatrix Class for console applications Pin
melmele9-Oct-03 3:00
membermelmele9-Oct-03 3:00 
GeneralMemory Leak Pin
John Theal19-Aug-03 9:30
memberJohn Theal19-Aug-03 9:30 
GeneralRe: Memory Leak Pin
phanduchuynh6-Jan-05 16:30
memberphanduchuynh6-Jan-05 16:30 
GeneralHelper class not needed. Pin
Axter23-Jul-03 11:33
memberAxter23-Jul-03 11:33 
Generaltype in CMatrixHelper operator Pin
Kevin Pinkerton24-Mar-03 3:51
memberKevin Pinkerton24-Mar-03 3:51 
GeneralRe: type in CMatrixHelper operator Pin
Kevin Pinkerton24-Mar-03 3:54
memberKevin Pinkerton24-Mar-03 3:54 
GeneralAdditional Functions Pin
David Day4-Feb-03 4:33
memberDavid Day4-Feb-03 4:33 
Questionsize limits? Pin
Anonymous3-Dec-02 11:38
sussAnonymous3-Dec-02 11:38 
AnswerRe: size limits? Pin
Roger Allen4-Dec-02 4:33
memberRoger Allen4-Dec-02 4:33 
GeneralRe: size limits? Pin
Michel Wassink12-Jan-03 20:41
memberMichel Wassink12-Jan-03 20:41 
GeneralRe: size limits? Pin
Scott19656-May-03 13:36
sussScott19656-May-03 13:36 
GeneralRe: size limits? Pin
Michel Wassink11-May-03 2:52
memberMichel Wassink11-May-03 2:52 
GeneralRe: size limits? Pin
phanduchuynh6-Jan-05 16:34
memberphanduchuynh6-Jan-05 16:34 
Generalmatrix operations Pin
Anonymous11-Nov-02 8:20
sussAnonymous11-Nov-02 8:20 
Generalmatrix operations Pin
by11-Nov-02 8:20
sussby11-Nov-02 8:20 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

| Advertise | Privacy | Terms of Use | Mobile
Web04 | 2.8.150603.1 | Last Updated 13 Aug 2002
Article Copyright 2002 by Roger Allen
Everything else Copyright © CodeProject, 1999-2015
Layout: fixed | fluid