Home Algorithms Matrices Transposition of a matrix
23 | 05 | 2017
Transposition of a matrix PDF Print E-mail
Algorithms - Matrices
Written by Jan Schulz   
Sunday, 13 July 2008 20:13

Transpose of a matrix

The transpose of a matrix M of m×n elements is the matrix MT with n×m elements, where M [i, j] = MT [j, i] for all indices of i and j. In other words the elements of the rows become the elements of the columns and vice versa. A square matrix is called symmetric, when M = MT. The here given function returns the transpose of a matrix of the type t2dVariantArrayDouble.

 

Algorithm

As initial step the passed InputMatrix is controlled whether it is rectangular of not. When the test succeeds the row vectors of InputMatrix are transposed to column vectors of OutputMatrix. When the test fails the function returns FALSE. The title arrays of the rows and columns are exchanged.

 

Source

Function mtx_Transpose (InputMatrix : T2dVariantArrayDouble; Var OutputMatrix : T2dVariantArrayDouble) : Boolean;
// The function mtxTranspose transposes a matrix. Thus every element of a
// rectangular matrix input [y, x] is transposed to the output [x, y].
// (c) Jan Schulz, February 2004, www.code10.info
Var RunnerX : Integer;
RunnerY : Integer;
MaxCols : Integer;
MaxRows : Integer;
Begin
mtx_Transpose := False;

// is the input matrix rectangular and get its dimensions
If mtx_IsRectangular (InputMatrix, MaxRows, MaxCols) THen
Begin

// create the output matrix and swap col and row size
mtx_Create (OutputMatrix, MaxCols, MaxRows, NAN, InputMatrix.MatrixName);

// copy elements from Input [y, x] to Output [x, y]
For RunnerY := High (InputMatrix.Cells) downto Low (InputMatrix.Cells) do
Begin
For RunnerX := High (InputMatrix.Cells [RunnerY]) downto 0 do
Begin
OutputMatrix.Cells [RunnerX, RunnerY] := InputMatrix.Cells [RunnerY, RunnerX];
end;
end;

// set the length of the arrays for the column and row titles
SetLength (OutputMatrix.ColTitle, High (InputMatrix.RowTitle) +1);
SetLength (OutputMatrix.RowTitle, High (InputMatrix.ColTitle) +1);

// copy the titles for the transposed matrix
For RunnerX := High (InputMatrix.ColTitle) downto 0 do
OutputMatrix.RowTitle [RunnerX] := InputMatrix.ColTitle [RunnerX];

For RunnerY := High (InputMatrix.RowTitle) downto 0 do
Outputmatrix.ColTitle [RunnerY] := InputMatrix.RowTitle [RunnerY];

mtx_Transpose := True;
end;
end;

Example

For a data matrix aInputMatrix of the type t2dVariantArrayDouble, populated with:

Data

Var1

Var2

Var3

Case1

1

1

1

Case2

1

1

0

Case3

2

2

2

Case4

10

10

10

Case5

11

11

11

Case6

10

5

0

the call of:

aBooleanVar := mtx_Transpose (aInputMatrix, aOutputMatrix);

returns TRUE and in aOutputMatrix the transposed matrix:

Data

Case1

Case2

Case3

Case4

Case5

Case6

Var1

1

1

2

10

11

10

Var2

1

1

2

10

11

5

Var3

1

0

2

10

11

0



 
Last Updated on Friday, 18 March 2011 18:06
 
Sponsored Links