How to inverse N x M matrix in Pascal

1 Answer

0 votes
program MatrixDemo;

const
  MaxRows = 3;
  MaxCols = 4;

type
  TMatrix = array[1..MaxRows, 1..MaxCols] of Integer;

procedure PrintMatrix(var M: TMatrix; Rows, Cols: Integer);
var
  i, j: Integer;
begin
  for i := 1 to Rows do
  begin
    for j := 1 to Cols do
      Write(M[i, j]:4);   { pad each number to width 4 }
    Writeln;
  end;
end;

procedure InverseMatrix(var M: TMatrix; Rows, Cols: Integer);
var
  i, j, r, c, counter, temp: Integer;
begin
  counter := 0;
  r := Rows;
  for i := 1 to Rows do
  begin
    c := Cols;
    for j := 1 to Cols do
    begin
      temp := M[i, j];
      M[i, j] := M[r, c];
      M[r, c] := temp;

      Inc(counter);
      if counter > (Rows * Cols) div 2 - 1 then
        Exit;

      Dec(c);
    end;
    Dec(r);
  end;
end;

var
  Matrix: TMatrix;
begin
  { initialize matrix }
  Matrix[1,1] := 1;  Matrix[1,2] := 2;  Matrix[1,3] := 3;  Matrix[1,4] := 4;
  Matrix[2,1] := 5;  Matrix[2,2] := 6;  Matrix[2,3] := 7;  Matrix[2,4] := 8;
  Matrix[3,1] := 9;  Matrix[3,2] := 10; Matrix[3,3] := 11; Matrix[3,4] := 12;

  Writeln('matrix:');
  PrintMatrix(Matrix, MaxRows, MaxCols);

  InverseMatrix(Matrix, MaxRows, MaxCols);

  Writeln;
  Writeln('inverse matrix:');
  PrintMatrix(Matrix, MaxRows, MaxCols);
end.



(*
run:

matrix:
   1   2   3   4
   5   6   7   8
   9  10  11  12

inverse matrix:
  12  11  10   9
   8   7   6   5
   4   3   2   1

*)

 



answered 1 day ago by avibootz
...