Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Semrush - keyword research tool

Create your online store today with Shopify

Turn ChatGPT, Claude, Gemini, And CoPilot Into Your Personal Assistant, Business Coach, Content Creator, And More

AFFILIATE MARKETING Your all-in-one performance engine Manage affiliates, creators, and customer referrals in one unified platform—turning every partnership into measurable growth

Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Disclosure: My content contains affiliate links.

43,240 questions

56,143 answers

573 users

How to transpose a matrix (swap rows and columns) in Pascal

1 Answer

0 votes
program TransposeMatrix;

{$mode objfpc}{$H+}

type
  TMatrix = array of array of Integer;

function Transpose(const M: TMatrix): TMatrix;
var
  rows, cols, i, j: Integer;
  R: TMatrix;  // local result
begin
  rows := Length(M);
  cols := Length(M[0]);

  SetLength(R, cols, rows);

  for i := 0 to rows - 1 do
    for j := 0 to cols - 1 do
      R[j][i] := M[i][j];

  Result := R; 
end;


procedure PrintMatrix(const M: TMatrix);
var
  i, j: Integer;
begin
  for i := 0 to High(M) do
  begin
    for j := 0 to High(M[i]) do
      Write(M[i][j], ' ');
    Writeln;
  end;
end;

var
  Matrix, T: TMatrix;

begin
  Matrix := [
    [1, 2, 3],
    [4, 5, 6],
    [7, 8, 9]
  ];

  T := Transpose(Matrix);
  PrintMatrix(T);
end.



(*
run:
        
1 4 7 
2 5 8 
3 6 9 
    
*)

 



answered May 25 by avibootz
...