2009-05-01 7 views
1

매트릭스를 사용하여 연산을 구현해야하며 매트릭스의 크기는 가변적이어야합니다. 내가 생각 해낸 유일한 해결책은 연결리스트를 사용하는 것입니다파스칼에서 행렬 연산을 구현하는 방법은 무엇입니까?

[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] ... 
    ... 

하지만 더 나은 (쉽게) 솔루션이 있습니까 .. 나에게 조금 복잡한 것 같습니다?

감사합니다.

답변

1

한 가지 방법은 메모리를 할당하기 위해 GetMem을 사용하는 것입니다. GetMem이 널리 지원되는 것 같습니다.

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; 
+0

MAXMATRIXDATA : Word = 10000; FreePascal에서 작동하지 않습니다 => MAXMATRIXDATA = 10000 작품 –

1

현대식 파스칼 변형 (Delphi)을 사용하면 동적 (런타임 크기) 배열을 만들 수 있습니다.

언어는 사용자가 직접 주소 지정 돌볼 수 다차원 동적 배열을 지원하지 않는 경우 :

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; 

훨씬 빨리 연결리스트를 다음보다 것이다 주소의이 종류.