Tag Archives: matrix

Basic Matrix operation in Lazarus/FreePascal

Well.. This is my first post about FreePascal (FPC)/Lazarus. I’ve been asked to create a simulation for artificial neural-network using backpropagation without using Matlab. So, I decided to use FreePascal/Lazarus to create it. Why? Because it’s challenging.. 😀

First problem that I need to overcome is how to mimic matrix arithmetic in FreePascal just like in Matlab. So, after some searching, I found satisfactory library called DynMatrix.

Download dynmatrix.zip file from here: http://paginas.fe.up.pt/~paco/pmwiki/index.php?n=DynMatrix.DynMatrix

Extract two files inside the archive, you’ll need only: dynmatrixutils.pas and dynmatrix.pas.

Use these two files in your project/form, example:

uses
  Classes, SysUtils, FileUtil, Forms, Controls, Graphics, Dialogs, Grids,
  StdCtrls, Spin, math, dynmatrix, dynmatrixutils;

Now, for the example usage:
Declare a matrix variables:

var
  A, B: TDMatrix;

Init a matrix into all zeros with 4 rows and 3 cols:

A:=Mzeros(4, 3);

Setting a value for an element in matrix:

A.setv(row_number, col_number, the_value);  //the value is a "double" type

Getting the value of an element:

the_value:=A.getv(row_number, col_number);

Matrix addition, subtraction, multiplication and matrix power:

C:=A+1;  //add with a constant
C:=A+B;  //add with a matrix
C:=A-1;  //substraction with constant
C:=A-B;  //substract with matrix
C:=3.4 * A; //multiply with a constant
C:=A * (-4.2);  //another form of multiplication
C:=A * B;  //multiply with another matrix
C:=A**4;  //matrix power with 4
C:=A**(-1);  //can also be powered with negative number

Matrix transpose, inverse and convolution

B:=A.t;   //transpose
B:=Minv(A);  //inverse matrix
C:=Mconv(A, B); //convolution

Converting string to matrix:

A:=StringToMatrix('1 2 3; 4 5 6');  //just like Matlab, convenient isn't it?

Creating “eye” matrix:

A:=Meye(4);  //4x4 "eye" matrix

Does this library also works on Delphi? Although I have Delphi, I haven’t tried it. So, no idea, but I’ve been looking at the source code and it seems it is OK to use it on Delphi Pascal. The dependecies is only on SysUtils, math and Classes