How to implement Matrix operations in Pascal?
Question
I need to implement operations with matrices and size of matrix has to be variable. The only solution I came up with is to use linked list:
[pointer to this row, pointer to another row] -> [element 1,1; link to another element] -> [element 1,2, link to another element] -> .... -> [nil]
|
v
[pointer to this row, pointer to another row] ...
...
But it seems to me a little bit complex.. Is there a better (and easier) solution?
Thank you guys!
Solution
One approach would be to use GetMem to allocate exactly enough memory. GetMem seems widely supported.
const
MAXMATRIXDATA: Word = 10000;
type
TMatrixDataType = Word;
TMatrixData = array[0..MAXMATRIXDATA] of TMatrixDataType;
PMatrixData = ^TMatrixData;
TMatrix = record
Rows, Cols: Word;
MatrixData: PMatrixData;
end;
PMatrix = ^TMatrix;
function CreateMatrix(Rows, Cols: Word): PMatrix;
var
Ret: PMatrix;
begin
New(Ret);
Ret^.Rows := Rows;
Ret^.Cols := Cols;
GetMem(Ret^.MatrixData,Rows*Cols*SizeOf(TMatrixDataType));
CreateMatrix := Ret;
end;
function GetMatrixData(Matrix: PMatrix; Row, Col: Word): TMatrixDataType;
begin
GetMatrixData := Matrix^.MatrixData^[(Row*Matrix^.Cols)+Col];
end;
procedure SetMatrixData(Matrix: PMatrix; Row, Col: Word; Val: TMatrixDataType);
begin
Matrix^.MatrixData^[(Row*Matrix^.Cols)+Col] := Val;
end;
OTHER TIPS
Any modern pascal variant (Delphi) will let you create dynamic (runtime sized) arrays.
If the language doesn't support multidimensional dynamic arrays you can take care of the addressing yourself:
var
rows, cols, total, i, j : integer;
cell : datatype;
begin
rows := ...;
cols := ...;
total := rows * cols;
matrix := ...(total);
cell := matrix[i * cols + j]; // matrix[row=i,col=j]
end;
This kind of addressing will be a lot faster than following linked lists.
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow