Matrix transposition: Difference between revisions
mNo edit summary |
Thundergnat (talk | contribs) m syntax highlighting fixup automation |
||
Line 3: | Line 3: | ||
<br><br> |
<br><br> |
||
=={{header|11l}}== |
=={{header|11l}}== |
||
< |
<syntaxhighlight lang="11l">F transpose(&matrix) |
||
V toRet = [[0] * matrix.len] * matrix[0].len |
V toRet = [[0] * matrix.len] * matrix[0].len |
||
L(row) (0 .< matrix.len) |
L(row) (0 .< matrix.len) |
||
Line 14: | Line 14: | ||
print(m) |
print(m) |
||
print("After Transposition") |
print("After Transposition") |
||
print(transpose(&m))</ |
print(transpose(&m))</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre> |
<pre> |
||
Line 23: | Line 23: | ||
</pre> |
</pre> |
||
=={{header|360 Assembly}}== |
=={{header|360 Assembly}}== |
||
< |
<syntaxhighlight lang="360asm">... |
||
KN EQU 3 |
KN EQU 3 |
||
KM EQU 5 |
KM EQU 5 |
||
Line 61: | Line 61: | ||
B LOOPI next i |
B LOOPI next i |
||
ELOOPI EQU * out of loop i |
ELOOPI EQU * out of loop i |
||
...</ |
...</syntaxhighlight> |
||
=={{header|68000 Assembly}}== |
=={{header|68000 Assembly}}== |
||
< |
<syntaxhighlight lang="68000devpac">Transpose2DArray_B: |
||
;INPUT: |
;INPUT: |
||
;A0 = POINTER TO SOURCE ARRAY |
;A0 = POINTER TO SOURCE ARRAY |
||
Line 92: | Line 92: | ||
MOVEM.L (SP)+,D2-D7 |
MOVEM.L (SP)+,D2-D7 |
||
RTS</ |
RTS</syntaxhighlight> |
||
=={{header|ACL2}}== |
=={{header|ACL2}}== |
||
< |
<syntaxhighlight lang="lisp">(defun cons-each (xs xss) |
||
(if (or (endp xs) (endp xss)) |
(if (or (endp xs) (endp xss)) |
||
nil |
nil |
||
Line 111: | Line 111: | ||
(list-each (first xss)) |
(list-each (first xss)) |
||
(cons-each (first xss) |
(cons-each (first xss) |
||
(transpose-list (rest xss)))))</ |
(transpose-list (rest xss)))))</syntaxhighlight> |
||
=={{header|Action!}}== |
=={{header|Action!}}== |
||
< |
<syntaxhighlight lang="action!">DEFINE PTR="CARD" |
||
TYPE Matrix=[ |
TYPE Matrix=[ |
||
Line 180: | Line 180: | ||
PutE() PrintE("Transpose:") |
PutE() PrintE("Transpose:") |
||
PrintMatrix(out) |
PrintMatrix(out) |
||
RETURN</ |
RETURN</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
[https://gitlab.com/amarok8bit/action-rosetta-code/-/raw/master/images/Matrix_transposition.png Screenshot from Atari 8-bit computer] |
[https://gitlab.com/amarok8bit/action-rosetta-code/-/raw/master/images/Matrix_transposition.png Screenshot from Atari 8-bit computer] |
||
Line 203: | Line 203: | ||
=={{header|ActionScript}}== |
=={{header|ActionScript}}== |
||
In ActionScript, multi-dimensional arrays are created by making an "Array of arrays" where each element is an array. |
In ActionScript, multi-dimensional arrays are created by making an "Array of arrays" where each element is an array. |
||
< |
<syntaxhighlight lang="actionscript">function transpose( m:Array):Array |
||
{ |
{ |
||
//Assume each element in m is an array. (If this were production code, use typeof to be sure) |
//Assume each element in m is an array. (If this were production code, use typeof to be sure) |
||
Line 225: | Line 225: | ||
var M:Array = transpose(m); |
var M:Array = transpose(m); |
||
for(var i:uint = 0; i < M.length; i++) |
for(var i:uint = 0; i < M.length; i++) |
||
trace(M[i]);</ |
trace(M[i]);</syntaxhighlight> |
||
=={{header|Ada}}== |
=={{header|Ada}}== |
||
Line 231: | Line 231: | ||
This example illustrates use of Transpose for the matrices built upon the standard type Float: |
This example illustrates use of Transpose for the matrices built upon the standard type Float: |
||
< |
<syntaxhighlight lang="ada">with Ada.Numerics.Real_Arrays; use Ada.Numerics.Real_Arrays; |
||
with Ada.Text_IO; use Ada.Text_IO; |
with Ada.Text_IO; use Ada.Text_IO; |
||
Line 257: | Line 257: | ||
Put_Line ("After Transposition:"); |
Put_Line ("After Transposition:"); |
||
Put (Transpose (Matrix)); |
Put (Transpose (Matrix)); |
||
end Matrix_Transpose;</ |
end Matrix_Transpose;</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre> |
<pre> |
||
Line 273: | Line 273: | ||
=={{header|Agda}}== |
=={{header|Agda}}== |
||
< |
<syntaxhighlight lang="agda">module Matrix where |
||
open import Data.Nat |
open import Data.Nat |
||
Line 286: | Line 286: | ||
a = (1 ∷ 2 ∷ 3 ∷ []) ∷ (4 ∷ 5 ∷ 6 ∷ []) ∷ [] |
a = (1 ∷ 2 ∷ 3 ∷ []) ∷ (4 ∷ 5 ∷ 6 ∷ []) ∷ [] |
||
b = transpose a</ |
b = transpose a</syntaxhighlight> |
||
'''b''' evaluates to the following normal form: |
'''b''' evaluates to the following normal form: |
||
< |
<syntaxhighlight lang="agda">(1 ∷ 4 ∷ []) ∷ (2 ∷ 5 ∷ []) ∷ (3 ∷ 6 ∷ []) ∷ []</syntaxhighlight> |
||
=={{header|ALGOL 68}}== |
=={{header|ALGOL 68}}== |
||
Line 297: | Line 297: | ||
{{works with|ALGOL 68G|Any - tested with release [http://sourceforge.net/projects/algol68/files/algol68g/algol68g-1.18.0/algol68g-1.18.0-9h.tiny.el5.centos.fc11.i386.rpm/download 1.18.0-9h.tiny]}} |
{{works with|ALGOL 68G|Any - tested with release [http://sourceforge.net/projects/algol68/files/algol68g/algol68g-1.18.0/algol68g-1.18.0-9h.tiny.el5.centos.fc11.i386.rpm/download 1.18.0-9h.tiny]}} |
||
{{wont work with|ELLA ALGOL 68|Any (with appropriate job cards) - tested with release [http://sourceforge.net/projects/algol68/files/algol68toc/algol68toc-1.8.8d/algol68toc-1.8-8d.fc9.i386.rpm/download 1.8-8d] - due to extensive use of FORMATted transput}} |
{{wont work with|ELLA ALGOL 68|Any (with appropriate job cards) - tested with release [http://sourceforge.net/projects/algol68/files/algol68toc/algol68toc-1.8.8d/algol68toc-1.8-8d.fc9.i386.rpm/download 1.8-8d] - due to extensive use of FORMATted transput}} |
||
< |
<syntaxhighlight lang="algol68">main:( |
||
[,]REAL m=((1, 1, 1, 1), |
[,]REAL m=((1, 1, 1, 1), |
||
Line 323: | Line 323: | ||
printf(($x"Transpose:"l$)); |
printf(($x"Transpose:"l$)); |
||
pprint((ZIP m)) |
pprint((ZIP m)) |
||
)</ |
)</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre> |
<pre> |
||
Line 334: | Line 334: | ||
</pre> |
</pre> |
||
=={{header|Amazing Hopper}}== |
=={{header|Amazing Hopper}}== |
||
<syntaxhighlight lang="amazing hopper"> |
|||
<lang Amazing Hopper> |
|||
#include<hopper.h> |
#include<hopper.h> |
||
#proto showarraydata(_X_) |
#proto showarraydata(_X_) |
||
Line 367: | Line 367: | ||
{"\nDIMENSION = ",nDims,"; ROWS = ",nRows,"; COLS = ",nCols,"\n"}, println |
{"\nDIMENSION = ",nDims,"; ROWS = ",nRows,"; COLS = ",nCols,"\n"}, println |
||
back |
back |
||
</syntaxhighlight> |
|||
</lang> |
|||
{{out}} |
{{out}} |
||
<pre> |
<pre> |
||
Line 400: | Line 400: | ||
=={{header|APL}}== |
=={{header|APL}}== |
||
If M is a matrix, ⍉M is its transpose. For example, |
If M is a matrix, ⍉M is its transpose. For example, |
||
< |
<syntaxhighlight lang="apl"> |
||
3 3⍴⍳10 |
3 3⍴⍳10 |
||
1 2 3 |
1 2 3 |
||
Line 409: | Line 409: | ||
2 5 8 |
2 5 8 |
||
3 6 9 |
3 6 9 |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|AppleScript}}== |
=={{header|AppleScript}}== |
||
Line 415: | Line 415: | ||
We can do this iteratively, by manually setting up two nested loops, and initialising iterators and empty lists, |
We can do this iteratively, by manually setting up two nested loops, and initialising iterators and empty lists, |
||
< |
<syntaxhighlight lang="applescript">on run |
||
transpose([[1, 2, 3], [4, 5, 6], [7, 8, 9], [10, 11, 12]]) |
transpose([[1, 2, 3], [4, 5, 6], [7, 8, 9], [10, 11, 12]]) |
||
Line 435: | Line 435: | ||
return lstTrans |
return lstTrans |
||
end transpose</ |
end transpose</syntaxhighlight> |
||
Line 442: | Line 442: | ||
{{trans|JavaScript}} |
{{trans|JavaScript}} |
||
< |
<syntaxhighlight lang="applescript">-- TRANSPOSE ----------------------------------------------------------------- |
||
-- transpose :: [[a]] -> [[a]] |
-- transpose :: [[a]] -> [[a]] |
||
Line 493: | Line 493: | ||
end script |
end script |
||
end if |
end if |
||
end mReturn</ |
end mReturn</syntaxhighlight> |
||
{{Out}} |
{{Out}} |
||
< |
<syntaxhighlight lang="applescript">{{1, 4, 7, 10}, {2, 5, 8, 11}, {3, 6, 9, 12}}</syntaxhighlight> |
||
=={{header|Arturo}}== |
=={{header|Arturo}}== |
||
< |
<syntaxhighlight lang="rebol">transpose: function [a][ |
||
X: size a |
X: size a |
||
Y: size first a |
Y: size first a |
||
Line 521: | Line 521: | ||
loop arr 'row -> print row |
loop arr 'row -> print row |
||
print "-------------" |
print "-------------" |
||
loop transpose arr 'row -> print row</ |
loop transpose arr 'row -> print row</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
Line 536: | Line 536: | ||
=={{header|AutoHotkey}}== |
=={{header|AutoHotkey}}== |
||
<syntaxhighlight lang="autohotkey">a = a |
|||
<lang AutoHotkey>a = a |
|||
m = 10 |
m = 10 |
||
n = 10 |
n = 10 |
||
Line 594: | Line 594: | ||
Return matrix |
Return matrix |
||
} |
} |
||
</syntaxhighlight> |
|||
</lang> |
|||
===Using Objects=== |
===Using Objects=== |
||
< |
<syntaxhighlight lang="autohotkey">Transpose(M){ |
||
R := [] |
R := [] |
||
for i, row in M |
for i, row in M |
||
Line 602: | Line 602: | ||
R[j,i] := col |
R[j,i] := col |
||
return R |
return R |
||
}</ |
}</syntaxhighlight> |
||
Examples:< |
Examples:<syntaxhighlight lang="autohotkey">Matrix := [[1,2,3],[4,5,6],[7,8,9],[10,11,12]] |
||
MsgBox % "" |
MsgBox % "" |
||
. "Original Matrix :`n" Print(Matrix) |
. "Original Matrix :`n" Print(Matrix) |
||
Line 613: | Line 613: | ||
Res .= (A_Index=1?"":"`t") col (Mod(A_Index,M[1].MaxIndex())?"":"`n") |
Res .= (A_Index=1?"":"`t") col (Mod(A_Index,M[1].MaxIndex())?"":"`n") |
||
return Trim(Res,"`n") |
return Trim(Res,"`n") |
||
}</ |
}</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre>Original Matrix : |
<pre>Original Matrix : |
||
Line 628: | Line 628: | ||
=={{header|AWK}}== |
=={{header|AWK}}== |
||
<syntaxhighlight lang="awk"> |
|||
<lang AWK> |
|||
# syntax: GAWK -f MATRIX_TRANSPOSITION.AWK filename |
# syntax: GAWK -f MATRIX_TRANSPOSITION.AWK filename |
||
{ if (NF > nf) { |
{ if (NF > nf) { |
||
Line 643: | Line 643: | ||
exit(0) |
exit(0) |
||
} |
} |
||
</syntaxhighlight> |
|||
</lang> |
|||
<p>input:</p> |
<p>input:</p> |
||
<pre> |
<pre> |
||
Line 658: | Line 658: | ||
</pre> |
</pre> |
||
===Using 2D-Arrays=== |
===Using 2D-Arrays=== |
||
< |
<syntaxhighlight lang="awk"># Usage: GAWK -f MATRIX_TRANSPOSITION.AWK filename |
||
{ |
{ |
||
i = NR |
i = NR |
||
Line 686: | Line 686: | ||
function max(m, n) { |
function max(m, n) { |
||
return m > n ? m : n |
return m > n ? m : n |
||
}</ |
}</syntaxhighlight> |
||
<p><b>Input:</b></p> |
<p><b>Input:</b></p> |
||
<pre> |
<pre> |
||
Line 731: | Line 731: | ||
=={{header|BASIC256}}== |
=={{header|BASIC256}}== |
||
< |
<syntaxhighlight lang="basic256">arraybase 1 |
||
dim matriz= {{78,19,30,12,36}, {49,10,65,42,50}, {30,93,24,78,10}, {39,68,27,64,29}} |
dim matriz= {{78,19,30,12,36}, {49,10,65,42,50}, {30,93,24,78,10}, {39,68,27,64,29}} |
||
dim mtranspuesta(matriz[,?], matriz[?,]) |
dim mtranspuesta(matriz[,?], matriz[?,]) |
||
Line 750: | Line 750: | ||
print |
print |
||
next fila |
next fila |
||
end</ |
end</syntaxhighlight> |
||
=={{header|BBC BASIC}}== |
=={{header|BBC BASIC}}== |
||
{{works with|BBC BASIC for Windows}} |
{{works with|BBC BASIC for Windows}} |
||
< |
<syntaxhighlight lang="bbcbasic"> INSTALL @lib$+"ARRAYLIB" |
||
DIM matrix(3,4), transpose(4,3) |
DIM matrix(3,4), transpose(4,3) |
||
Line 776: | Line 776: | ||
NEXT |
NEXT |
||
PRINT |
PRINT |
||
NEXT row%</ |
NEXT row%</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre> |
<pre> |
||
Line 793: | Line 793: | ||
=={{header|Burlesque}}== |
=={{header|Burlesque}}== |
||
< |
<syntaxhighlight lang="burlesque"> |
||
blsq ) {{78 19 30 12 36}{49 10 65 42 50}{30 93 24 78 10}{39 68 27 64 29}}tpsp |
blsq ) {{78 19 30 12 36}{49 10 65 42 50}{30 93 24 78 10}{39 68 27 64 29}}tpsp |
||
78 49 30 39 |
78 49 30 39 |
||
Line 800: | Line 800: | ||
12 42 78 64 |
12 42 78 64 |
||
36 50 10 29 |
36 50 10 29 |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|C}}== |
=={{header|C}}== |
||
Transpose a 2D double array. |
Transpose a 2D double array. |
||
< |
<syntaxhighlight lang="c">#include <stdio.h> |
||
void transpose(void *dest, void *src, int src_h, int src_w) |
void transpose(void *dest, void *src, int src_h, int src_w) |
||
Line 828: | Line 828: | ||
printf("%g%c", b[i][j], j == 2 ? '\n' : ' '); |
printf("%g%c", b[i][j], j == 2 ? '\n' : ' '); |
||
return 0; |
return 0; |
||
}</ |
}</syntaxhighlight> |
||
Transpose a matrix of size w x h in place with only O(1) space and without moving any element more than once. See the [[wp:In-place_matrix_transposition|Wikipedia article]] for more information. |
Transpose a matrix of size w x h in place with only O(1) space and without moving any element more than once. See the [[wp:In-place_matrix_transposition|Wikipedia article]] for more information. |
||
< |
<syntaxhighlight lang="c">#include <stdio.h> |
||
void transpose(double *m, int w, int h) |
void transpose(double *m, int w, int h) |
||
Line 880: | Line 880: | ||
return 0; |
return 0; |
||
}</ |
}</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre> |
<pre> |
||
Line 896: | Line 896: | ||
=={{header|C sharp|C#}}== |
=={{header|C sharp|C#}}== |
||
< |
<syntaxhighlight lang="csharp">using System; |
||
using System.Text; |
using System.Text; |
||
Line 927: | Line 927: | ||
} |
} |
||
} |
} |
||
}</ |
}</syntaxhighlight> |
||
=={{header|C++}}== |
=={{header|C++}}== |
||
Line 933: | Line 933: | ||
{{libheader|Boost.uBLAS}} |
{{libheader|Boost.uBLAS}} |
||
< |
<syntaxhighlight lang="cpp">#include <boost/numeric/ublas/matrix.hpp> |
||
#include <boost/numeric/ublas/io.hpp> |
#include <boost/numeric/ublas/io.hpp> |
||
Line 947: | Line 947: | ||
std::cout << trans(m) << std::endl; |
std::cout << trans(m) << std::endl; |
||
}</ |
}</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
Line 956: | Line 956: | ||
===Generic solution=== |
===Generic solution=== |
||
;main.cpp |
;main.cpp |
||
< |
<syntaxhighlight lang="cpp">#include <iostream> |
||
#include "matrix.h" |
#include "matrix.h" |
||
Line 994: | Line 994: | ||
} |
} |
||
} /* main() */</ |
} /* main() */</syntaxhighlight> |
||
;matrix.h |
;matrix.h |
||
< |
<syntaxhighlight lang="cpp">#ifndef _MATRIX_H |
||
#define _MATRIX_H |
#define _MATRIX_H |
||
Line 1,190: | Line 1,190: | ||
} |
} |
||
#endif /* _MATRIX_H */</ |
#endif /* _MATRIX_H */</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
Line 1,205: | Line 1,205: | ||
===Easy Mode=== |
===Easy Mode=== |
||
< |
<syntaxhighlight lang="cpp">#include <iostream> |
||
int main(){ |
int main(){ |
||
Line 1,240: | Line 1,240: | ||
return 0; |
return 0; |
||
}</ |
}</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre> |
<pre> |
||
Line 1,257: | Line 1,257: | ||
=={{header|Clojure}}== |
=={{header|Clojure}}== |
||
< |
<syntaxhighlight lang="lisp">(defmulti matrix-transpose |
||
"Switch rows with columns." |
"Switch rows with columns." |
||
class) |
class) |
||
Line 1,268: | Line 1,268: | ||
[mtx] |
[mtx] |
||
(apply mapv vector mtx)) |
(apply mapv vector mtx)) |
||
</syntaxhighlight> |
|||
</lang> |
|||
{{out}} |
{{out}} |
||
<pre>=> (matrix-transpose [[1 2 3] [4 5 6]]) |
<pre>=> (matrix-transpose [[1 2 3] [4 5 6]]) |
||
Line 1,274: | Line 1,274: | ||
=={{header|CoffeeScript}}== |
=={{header|CoffeeScript}}== |
||
< |
<syntaxhighlight lang="coffeescript">transpose = (matrix) -> |
||
(t[i] for t in matrix) for i in [0...matrix[0].length]</ |
(t[i] for t in matrix) for i in [0...matrix[0].length]</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre> |
<pre> |
||
Line 1,285: | Line 1,285: | ||
=={{header|Common Lisp}}== |
=={{header|Common Lisp}}== |
||
If the matrix is given as a list: |
If the matrix is given as a list: |
||
< |
<syntaxhighlight lang="lisp">(defun transpose (m) |
||
(apply #'mapcar #'list m))</ |
(apply #'mapcar #'list m))</syntaxhighlight> |
||
If the matrix A is given as a 2D array: |
If the matrix A is given as a 2D array: |
||
< |
<syntaxhighlight lang="lisp">;; Transpose a mxn matrix A to a nxm matrix B=A'. |
||
(defun mtp (A) |
(defun mtp (A) |
||
(let* ((m (array-dimension A 0)) |
(let* ((m (array-dimension A 0)) |
||
Line 1,298: | Line 1,298: | ||
(setf (aref B j i) |
(setf (aref B j i) |
||
(aref A i j)))) |
(aref A i j)))) |
||
B))</ |
B))</syntaxhighlight> |
||
=={{header|D}}== |
=={{header|D}}== |
||
===Standard Version=== |
===Standard Version=== |
||
< |
<syntaxhighlight lang="d">void main() { |
||
import std.stdio, std.range; |
import std.stdio, std.range; |
||
Line 1,309: | Line 1,309: | ||
[18, 19, 20, 21]]; |
[18, 19, 20, 21]]; |
||
writefln("%(%(%2d %)\n%)", M.transposed); |
writefln("%(%(%2d %)\n%)", M.transposed); |
||
}</ |
}</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre>10 14 18 |
<pre>10 14 18 |
||
Line 1,317: | Line 1,317: | ||
===Locally Procedural Style=== |
===Locally Procedural Style=== |
||
< |
<syntaxhighlight lang="d">T[][] transpose(T)(in T[][] m) pure nothrow { |
||
auto r = new typeof(return)(m[0].length, m.length); |
auto r = new typeof(return)(m[0].length, m.length); |
||
foreach (immutable nr, const row; m) |
foreach (immutable nr, const row; m) |
||
Line 1,332: | Line 1,332: | ||
[18, 19, 20, 21]]; |
[18, 19, 20, 21]]; |
||
writefln("%(%(%2d %)\n%)", M.transpose); |
writefln("%(%(%2d %)\n%)", M.transpose); |
||
}</ |
}</syntaxhighlight> |
||
Same output. |
Same output. |
||
===Functional Style=== |
===Functional Style=== |
||
< |
<syntaxhighlight lang="d">import std.stdio, std.algorithm, std.range, std.functional; |
||
auto transpose(T)(in T[][] m) pure nothrow { |
auto transpose(T)(in T[][] m) pure nothrow { |
||
Line 1,347: | Line 1,347: | ||
[18, 19, 20, 21]]; |
[18, 19, 20, 21]]; |
||
writefln("%(%(%2d %)\n%)", M.transpose); |
writefln("%(%(%2d %)\n%)", M.transpose); |
||
}</ |
}</syntaxhighlight> |
||
Same output. |
Same output. |
||
=={{header|Delphi}}== |
=={{header|Delphi}}== |
||
See [[#Pascal]]; |
See [[#Pascal]]; |
||
=={{header|EchoLisp}}== |
=={{header|EchoLisp}}== |
||
< |
<syntaxhighlight lang="scheme"> |
||
(lib 'matrix) |
(lib 'matrix) |
||
Line 1,363: | Line 1,363: | ||
0 2 4 |
0 2 4 |
||
1 3 5 |
1 3 5 |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|EDSAC order code}}== |
=={{header|EDSAC order code}}== |
||
In these two programs the matrix elements are stored in consecutive memory locations, in row-major order (that is, the 1st row from left to right, then the 2nd row, etc). For simplicity, matrix elements are short values, each occupying one memory location. The programs could be modified so that each element occupies two memory locations, as in the EDSAC library subroutines for vectors and matrices. |
In these two programs the matrix elements are stored in consecutive memory locations, in row-major order (that is, the 1st row from left to right, then the 2nd row, etc). For simplicity, matrix elements are short values, each occupying one memory location. The programs could be modified so that each element occupies two memory locations, as in the EDSAC library subroutines for vectors and matrices. |
||
===Create a new matrix=== |
===Create a new matrix=== |
||
< |
<syntaxhighlight lang="edsac"> |
||
[Demo of matrix transposition. Not in place, creates a new matrix. |
[Demo of matrix transposition. Not in place, creates a new matrix. |
||
EDSAC, Initial Orders 2.] |
EDSAC, Initial Orders 2.] |
||
Line 1,481: | Line 1,481: | ||
E12Z [enter at 12 (relative)] |
E12Z [enter at 12 (relative)] |
||
PF [accumulator = 0 on entry] |
PF [accumulator = 0 on entry] |
||
</syntaxhighlight> |
|||
</lang> |
|||
{{out}} |
{{out}} |
||
<pre> |
<pre> |
||
Line 1,497: | Line 1,497: | ||
{{trans|C}} |
{{trans|C}} |
||
That's a neat C program after the complications on Wikipedia. The way EDSAC handles arrays makes it convenient to modify the second half of the program. In C, the updated value of "next" has to be parked in another variable until m[next] (old "next") has been assigned to. In EDSAC, the instruction that assigns to m[next] can be planted before "next" is updated, and won't be affected by that update. Once the EDSAC program has been modified in this way, the code to update "next" is the same in both halves of the program and can be taken out as a subroutine. |
That's a neat C program after the complications on Wikipedia. The way EDSAC handles arrays makes it convenient to modify the second half of the program. In C, the updated value of "next" has to be parked in another variable until m[next] (old "next") has been assigned to. In EDSAC, the instruction that assigns to m[next] can be planted before "next" is updated, and won't be affected by that update. Once the EDSAC program has been modified in this way, the code to update "next" is the same in both halves of the program and can be taken out as a subroutine. |
||
< |
<syntaxhighlight lang="edsac"> |
||
[Transpose a matrix in place. EDSAC, Initial Orders 2.] |
[Transpose a matrix in place. EDSAC, Initial Orders 2.] |
||
..PZ [blank tape and terminator] |
..PZ [blank tape and terminator] |
||
Line 1,587: | Line 1,587: | ||
T10@A9@A8@U9@TFA23@A2FT23@A10@A2FG19@A3@T10FA4@T11FA5@T12FA6@T13F |
T10@A9@A8@U9@TFA23@A2FT23@A10@A2FG19@A3@T10FA4@T11FA5@T12FA6@T13F |
||
A38@GMO1@O2@A42@GXA10FTFA11FT10FAFT11FA50@GMO@ZFE11ZPF |
A38@GMO1@O2@A42@GXA10FTFA11FT10FAFT11FA50@GMO@ZFE11ZPF |
||
</syntaxhighlight> |
|||
</lang> |
|||
{{out}} |
{{out}} |
||
<pre> |
<pre> |
||
Line 1,605: | Line 1,605: | ||
=={{header|Elixir}}== |
=={{header|Elixir}}== |
||
< |
<syntaxhighlight lang="elixir">m = [[1, 1, 1, 1], |
||
[2, 4, 8, 16], |
[2, 4, 8, 16], |
||
[3, 9, 27, 81], |
[3, 9, 27, 81], |
||
Line 1,613: | Line 1,613: | ||
transpose = fn(m)-> List.zip(m) |> Enum.map(&Tuple.to_list(&1)) end |
transpose = fn(m)-> List.zip(m) |> Enum.map(&Tuple.to_list(&1)) end |
||
IO.inspect transpose.(m)</ |
IO.inspect transpose.(m)</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
Line 1,623: | Line 1,623: | ||
Sample originally from ftp://ftp.dra.hmg.gb/pub/ella (a now dead link) - Public release. |
Sample originally from ftp://ftp.dra.hmg.gb/pub/ella (a now dead link) - Public release. |
||
Code for matrix transpose hardware design verification:< |
Code for matrix transpose hardware design verification:<syntaxhighlight lang="ella">MAC TRANSPOSE = ([INT n][INT m]TYPE t: matrix) -> [m][n]t: |
||
[INT i = 1..m] [INT j = 1..n] matrix[j][i].</ |
[INT i = 1..m] [INT j = 1..n] matrix[j][i].</syntaxhighlight> |
||
=={{header|Emacs Lisp}}== |
=={{header|Emacs Lisp}}== |
||
Line 1,630: | Line 1,630: | ||
{{libheader|cl-lib}} |
{{libheader|cl-lib}} |
||
< |
<syntaxhighlight lang="lisp">(require 'cl-lib) |
||
(defun transpose (m) |
(defun transpose (m) |
||
Line 1,636: | Line 1,636: | ||
;;test for transposition function |
;;test for transposition function |
||
(transpose '((2 3 4 5) (3 5 6 9) (9 9 9 9)))</ |
(transpose '((2 3 4 5) (3 5 6 9) (9 9 9 9)))</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
Line 1,650: | Line 1,650: | ||
A nice introduction http://langintro.com/erlang/article2/ which is much more explicit. |
A nice introduction http://langintro.com/erlang/article2/ which is much more explicit. |
||
< |
<syntaxhighlight lang="erlang"> |
||
-module(transmatrix). |
-module(transmatrix). |
||
-export([trans/1,transL/1]). |
-export([trans/1,transL/1]). |
||
Line 1,669: | Line 1,669: | ||
transL([ [] | List] ) -> transL(List); |
transL([ [] | List] ) -> transL(List); |
||
transL([]) -> []. |
transL([]) -> []. |
||
</syntaxhighlight> |
|||
</lang> |
|||
{{out}} |
{{out}} |
||
Line 1,682: | Line 1,682: | ||
=={{header|Euphoria}}== |
=={{header|Euphoria}}== |
||
< |
<syntaxhighlight lang="euphoria">function transpose(sequence in) |
||
sequence out |
sequence out |
||
out = repeat(repeat(0,length(in)),length(in[1])) |
out = repeat(repeat(0,length(in)),length(in[1])) |
||
Line 1,700: | Line 1,700: | ||
} |
} |
||
? transpose(m)</ |
? transpose(m)</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
Line 1,783: | Line 1,783: | ||
=={{header|F_Sharp|F#}}== |
=={{header|F_Sharp|F#}}== |
||
Very straightforward solution... |
Very straightforward solution... |
||
< |
<syntaxhighlight lang="fsharp">let transpose (mtx : _ [,]) = Array2D.init (mtx.GetLength 1) (mtx.GetLength 0) (fun x y -> mtx.[y,x])</syntaxhighlight> |
||
=={{header|Factor}}== |
=={{header|Factor}}== |
||
<code>flip</code> can be used. |
<code>flip</code> can be used. |
||
< |
<syntaxhighlight lang="factor">( scratchpad ) { { 1 2 3 } { 4 5 6 } } flip . |
||
{ { 1 4 } { 2 5 } { 3 6 } }</ |
{ { 1 4 } { 2 5 } { 3 6 } }</syntaxhighlight> |
||
=={{header|Fermat}}== |
=={{header|Fermat}}== |
||
Matrix transpose is built in. |
Matrix transpose is built in. |
||
< |
<syntaxhighlight lang="fermat"> |
||
Array a[3,1] |
Array a[3,1] |
||
[a]:=[(1,2,3)] |
[a]:=[(1,2,3)] |
||
Line 1,798: | Line 1,798: | ||
[a] |
[a] |
||
[b] |
[b] |
||
</syntaxhighlight> |
|||
</lang> |
|||
{{out}} |
{{out}} |
||
<pre> |
<pre> |
||
Line 1,810: | Line 1,810: | ||
{{libheader|Forth Scientific Library}} |
{{libheader|Forth Scientific Library}} |
||
{{works with|gforth|0.7.9_20170308}} |
{{works with|gforth|0.7.9_20170308}} |
||
< |
<syntaxhighlight lang="forth">S" fsl-util.fs" REQUIRED |
||
S" fsl/dynmem.seq" REQUIRED |
S" fsl/dynmem.seq" REQUIRED |
||
: F+! ( addr -- ) ( F: r -- ) DUP F@ F+ F! ; |
: F+! ( addr -- ) ( F: r -- ) DUP F@ F+ F! ; |
||
Line 1,821: | Line 1,821: | ||
a{{ 5 3 & b{{ transpose |
a{{ 5 3 & b{{ transpose |
||
3 5 b{{ }}fprint</ |
3 5 b{{ }}fprint</syntaxhighlight> |
||
=={{header|Fortran}}== |
=={{header|Fortran}}== |
||
In ISO Fortran 90 or later, use the TRANSPOSE intrinsic function: |
In ISO Fortran 90 or later, use the TRANSPOSE intrinsic function: |
||
< |
<syntaxhighlight lang="fortran">integer, parameter :: n = 3, m = 5 |
||
real, dimension(n,m) :: a = reshape( (/ (i,i=1,n*m) /), (/ n, m /) ) |
real, dimension(n,m) :: a = reshape( (/ (i,i=1,n*m) /), (/ n, m /) ) |
||
real, dimension(m,n) :: b |
real, dimension(m,n) :: b |
||
Line 1,837: | Line 1,837: | ||
do j = 1, m |
do j = 1, m |
||
print *, b(j,:) |
print *, b(j,:) |
||
end do</ |
end do</syntaxhighlight> |
||
In ANSI FORTRAN 77 with MIL-STD-1753 extensions or later, use nested structured DO loops: |
In ANSI FORTRAN 77 with MIL-STD-1753 extensions or later, use nested structured DO loops: |
||
< |
<syntaxhighlight lang="fortran">REAL A(3,5), B(5,3) |
||
DATA ((A(I,J),I=1,3),J=1,5) /1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15/ |
DATA ((A(I,J),I=1,3),J=1,5) /1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15/ |
||
Line 1,847: | Line 1,847: | ||
B(J,I) = A(I,J) |
B(J,I) = A(I,J) |
||
END DO |
END DO |
||
END DO</ |
END DO</syntaxhighlight> |
||
In ANSI FORTRAN 66 or later, use nested labeled DO loops: |
In ANSI FORTRAN 66 or later, use nested labeled DO loops: |
||
< |
<syntaxhighlight lang="fortran"> REAL A(3,5), B(5,3) |
||
DATA ((A(I,J),I=1,3),J=1,5) /1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15/ |
DATA ((A(I,J),I=1,3),J=1,5) /1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15/ |
||
Line 1,857: | Line 1,857: | ||
B(J,I) = A(I,J) |
B(J,I) = A(I,J) |
||
20 CONTINUE |
20 CONTINUE |
||
10 CONTINUE</ |
10 CONTINUE</syntaxhighlight> |
||
Explicit transposition via DO-loops was available from the start. Less obvious is that Fortran uses what is called "column major" order rather than "row major", which is to say that consecutive elements of the array are stored in memory with indices counting down the columns first, not along the rows. The above examples acknowledge this in the DATA statement with the <code>((A(row,col),row=1,3),col=1,5)</code> which could therefore be replaced with just <code>A</code>, however one could use <code>((A(row,col),col=1,5),row=1,3)</code> instead and the DATA values could be arranged so as to appear in the same layout as one expects for a matrix. Consider < |
Explicit transposition via DO-loops was available from the start. Less obvious is that Fortran uses what is called "column major" order rather than "row major", which is to say that consecutive elements of the array are stored in memory with indices counting down the columns first, not along the rows. The above examples acknowledge this in the DATA statement with the <code>((A(row,col),row=1,3),col=1,5)</code> which could therefore be replaced with just <code>A</code>, however one could use <code>((A(row,col),col=1,5),row=1,3)</code> instead and the DATA values could be arranged so as to appear in the same layout as one expects for a matrix. Consider <syntaxhighlight lang="fortran"> DIMENSION A(3,5),B(5,3),C(5,3) |
||
EQUIVALENCE (A,C) !Occupy the same storage. |
EQUIVALENCE (A,C) !Occupy the same storage. |
||
DATA A/ |
DATA A/ |
||
Line 1,886: | Line 1,886: | ||
1 FORMAT (5F6.1) !Five values per line. |
1 FORMAT (5F6.1) !Five values per line. |
||
2 FORMAT (3F6.1) !Three values per line. |
2 FORMAT (3F6.1) !Three values per line. |
||
END</ |
END</syntaxhighlight> |
||
Output: |
Output: |
||
Line 1,922: | Line 1,922: | ||
=={{header|FreeBASIC}}== |
=={{header|FreeBASIC}}== |
||
< |
<syntaxhighlight lang="freebasic">Dim matriz(0 To 3, 0 To 4) As Integer = {{78,19,30,12,36},_ |
||
{49,10,65,42,50},_ |
{49,10,65,42,50},_ |
||
{30,93,24,78,10},_ |
{30,93,24,78,10},_ |
||
Line 1,944: | Line 1,944: | ||
Print |
Print |
||
Next fila |
Next fila |
||
Sleep</ |
Sleep</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre> |
<pre> |
||
Line 1,962: | Line 1,962: | ||
=={{header|Frink}}== |
=={{header|Frink}}== |
||
The built-in array method <CODE>transpose</CODE> transposes a 2-dimensional array. |
The built-in array method <CODE>transpose</CODE> transposes a 2-dimensional array. |
||
< |
<syntaxhighlight lang="frink"> |
||
a = [[1,2,3], |
a = [[1,2,3], |
||
[4,5,6], |
[4,5,6], |
||
[7,8,9]] |
[7,8,9]] |
||
joinln[a.transpose[]] |
joinln[a.transpose[]] |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|Fōrmulæ}}== |
=={{header|Fōrmulæ}}== |
||
Line 1,978: | Line 1,978: | ||
=={{header|GAP}}== |
=={{header|GAP}}== |
||
< |
<syntaxhighlight lang="gap">originalMatrix := [[1, 1, 1, 1], |
||
[2, 4, 8, 16], |
[2, 4, 8, 16], |
||
[3, 9, 27, 81], |
[3, 9, 27, 81], |
||
[4, 16, 64, 256], |
[4, 16, 64, 256], |
||
[5, 25, 125, 625]]; |
[5, 25, 125, 625]]; |
||
transposedMatrix := TransposedMat(originalMatrix);</ |
transposedMatrix := TransposedMat(originalMatrix);</syntaxhighlight> |
||
=={{header|Go}}== |
=={{header|Go}}== |
||
===Library gonum/mat=== |
===Library gonum/mat=== |
||
< |
<syntaxhighlight lang="go">package main |
||
import ( |
import ( |
||
Line 2,003: | Line 2,003: | ||
fmt.Println() |
fmt.Println() |
||
fmt.Println(mat.Formatted(m.T())) |
fmt.Println(mat.Formatted(m.T())) |
||
}</ |
}</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre> |
<pre> |
||
Line 2,015: | Line 2,015: | ||
===Library go.matrix=== |
===Library go.matrix=== |
||
< |
<syntaxhighlight lang="go">package main |
||
import ( |
import ( |
||
Line 2,033: | Line 2,033: | ||
fmt.Println("transpose:") |
fmt.Println("transpose:") |
||
fmt.Println(m) |
fmt.Println(m) |
||
}</ |
}</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre> |
<pre> |
||
Line 2,047: | Line 2,047: | ||
===2D representation=== |
===2D representation=== |
||
Go arrays and slices are only one-dimensional. The obvious way to represent two-dimensional arrays is with a slice of slices: |
Go arrays and slices are only one-dimensional. The obvious way to represent two-dimensional arrays is with a slice of slices: |
||
< |
<syntaxhighlight lang="go">package main |
||
import "fmt" |
import "fmt" |
||
Line 2,081: | Line 2,081: | ||
} |
} |
||
return r |
return r |
||
}</ |
}</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre>[1 2 3] |
<pre>[1 2 3] |
||
Line 2,092: | Line 2,092: | ||
A flat element representation with a stride is almost always better. |
A flat element representation with a stride is almost always better. |
||
< |
<syntaxhighlight lang="go">package main |
||
import "fmt" |
import "fmt" |
||
Line 2,142: | Line 2,142: | ||
} |
} |
||
return r |
return r |
||
}</ |
}</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre> |
<pre> |
||
Line 2,157: | Line 2,157: | ||
{{trans|C}} |
{{trans|C}} |
||
Note representation is "flat," as above, but without the fluff of constructing from rows. |
Note representation is "flat," as above, but without the fluff of constructing from rows. |
||
< |
<syntaxhighlight lang="go">package main |
||
import "fmt" |
import "fmt" |
||
Line 2,217: | Line 2,217: | ||
} |
} |
||
m.stride = h |
m.stride = h |
||
}</ |
}</syntaxhighlight> |
||
Output same as above. |
Output same as above. |
||
=={{header|Groovy}}== |
=={{header|Groovy}}== |
||
The Groovy extensions to the List class provides a transpose method: |
The Groovy extensions to the List class provides a transpose method: |
||
< |
<syntaxhighlight lang="groovy">def matrix = [ [ 1, 2, 3, 4 ], |
||
[ 5, 6, 7, 8 ] ] |
[ 5, 6, 7, 8 ] ] |
||
Line 2,229: | Line 2,229: | ||
def transpose = matrix.transpose() |
def transpose = matrix.transpose() |
||
transpose.each { println it }</ |
transpose.each { println it }</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
Line 2,242: | Line 2,242: | ||
=={{header|Haskell}}== |
=={{header|Haskell}}== |
||
For matrices represented as lists, there's ''transpose'': |
For matrices represented as lists, there's ''transpose'': |
||
< |
<syntaxhighlight lang="haskell">*Main> transpose [[1,2],[3,4],[5,6]] |
||
[[1,3,5],[2,4,6]]</ |
[[1,3,5],[2,4,6]]</syntaxhighlight> |
||
For matrices in arrays, one can use ''ixmap'': |
For matrices in arrays, one can use ''ixmap'': |
||
< |
<syntaxhighlight lang="haskell">import Data.Array |
||
swap (x,y) = (y,x) |
swap (x,y) = (y,x) |
||
Line 2,252: | Line 2,252: | ||
transpArray :: (Ix a, Ix b) => Array (a,b) e -> Array (b,a) e |
transpArray :: (Ix a, Ix b) => Array (a,b) e -> Array (b,a) e |
||
transpArray a = ixmap (swap l, swap u) swap a where |
transpArray a = ixmap (swap l, swap u) swap a where |
||
(l,u) = bounds a</ |
(l,u) = bounds a</syntaxhighlight> |
||
Using ''zipWith'' assuming a matrix is a list of row lists: |
Using ''zipWith'' assuming a matrix is a list of row lists: |
||
< |
<syntaxhighlight lang="haskell"> |
||
tpose [ms] = [[m] | m <- ms] |
tpose [ms] = [[m] | m <- ms] |
||
tpose (ms:mss) = zipWith (:) ms (tpose mss) |
tpose (ms:mss) = zipWith (:) ms (tpose mss) |
||
</syntaxhighlight> |
|||
</lang> |
|||
{{out}} |
{{out}} |
||
<pre> |
<pre> |
||
Line 2,266: | Line 2,266: | ||
===With Numeric.LinearAlgebra=== |
===With Numeric.LinearAlgebra=== |
||
< |
<syntaxhighlight lang="haskell">import Numeric.LinearAlgebra |
||
a :: Matrix I |
a :: Matrix I |
||
Line 2,276: | Line 2,276: | ||
main = do |
main = do |
||
print $ a |
print $ a |
||
print $ tr a</ |
print $ tr a</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre>(3><2) |
<pre>(3><2) |
||
Line 2,287: | Line 2,287: | ||
=={{header|Haxe}}== |
=={{header|Haxe}}== |
||
< |
<syntaxhighlight lang="haxe">class Matrix { |
||
static function main() { |
static function main() { |
||
var m = [ [1, 1, 1, 1], |
var m = [ [1, 1, 1, 1], |
||
Line 2,303: | Line 2,303: | ||
for(a in aa) Sys.println(a); |
for(a in aa) Sys.println(a); |
||
} |
} |
||
}</ |
}</syntaxhighlight> |
||
{{Out}} |
{{Out}} |
||
<pre>[1,1,1,1] |
<pre>[1,1,1,1] |
||
Line 2,316: | Line 2,316: | ||
=={{header|HicEst}}== |
=={{header|HicEst}}== |
||
< |
<syntaxhighlight lang="hicest">REAL :: mtx(2, 4) |
||
mtx = 1.1 * $ |
mtx = 1.1 * $ |
||
Line 2,322: | Line 2,322: | ||
SOLVE(Matrix=mtx, Transpose=mtx) |
SOLVE(Matrix=mtx, Transpose=mtx) |
||
WRITE() mtx</ |
WRITE() mtx</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre>1.1 2.2 3.3 4.4 |
<pre>1.1 2.2 3.3 4.4 |
||
Line 2,333: | Line 2,333: | ||
=={{header|Hope}}== |
=={{header|Hope}}== |
||
< |
<syntaxhighlight lang="hope">uses lists; |
||
dec transpose : list (list alpha) -> list (list alpha); |
dec transpose : list (list alpha) -> list (list alpha); |
||
--- transpose ([]::_) <= []; |
--- transpose ([]::_) <= []; |
||
--- transpose n <= map head n :: transpose (map tail n);</ |
--- transpose n <= map head n :: transpose (map tail n);</syntaxhighlight> |
||
=={{header|Icon}} and {{header|Unicon}}== |
=={{header|Icon}} and {{header|Unicon}}== |
||
< |
<syntaxhighlight lang="icon">procedure transpose_matrix (matrix) |
||
result := [] |
result := [] |
||
# for each column |
# for each column |
||
Line 2,366: | Line 2,366: | ||
write ("Transposed:") |
write ("Transposed:") |
||
print_matrix (transposed) |
print_matrix (transposed) |
||
end</ |
end</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre> |
<pre> |
||
Line 2,380: | Line 2,380: | ||
=={{header|IDL}}== |
=={{header|IDL}}== |
||
Standard IDL function <tt>transpose()</tt> |
Standard IDL function <tt>transpose()</tt> |
||
< |
<syntaxhighlight lang="idl">m=[[1,1,1,1],[2, 4, 8, 16],[3, 9,27, 81],[5, 25,125, 625]] |
||
print,transpose(m)</ |
print,transpose(m)</syntaxhighlight> |
||
=={{header|Idris}}== |
=={{header|Idris}}== |
||
< |
<syntaxhighlight lang="idris">Idris> transpose [[1,2],[3,4],[5,6]] |
||
[[1, 3, 5], [2, 4, 6]] : List (List Integer)</ |
[[1, 3, 5], [2, 4, 6]] : List (List Integer)</syntaxhighlight> |
||
=={{header|J}}== |
=={{header|J}}== |
||
Line 2,392: | Line 2,392: | ||
'''Example:''' |
'''Example:''' |
||
< |
<syntaxhighlight lang="j"> ]matrix=: (^/ }:) >:i.5 NB. make and show example matrix |
||
1 1 1 1 |
1 1 1 1 |
||
2 4 8 16 |
2 4 8 16 |
||
Line 2,402: | Line 2,402: | ||
1 4 9 16 25 |
1 4 9 16 25 |
||
1 8 27 64 125 |
1 8 27 64 125 |
||
1 16 81 256 625</ |
1 16 81 256 625</syntaxhighlight> |
||
As an aside, note that <code>.</code> and <code>:</code> are token forming suffixes (if they immediately follow a token forming character, they are a part of the token). This usage is in analogy to the use of [[wp:Diacritic|diacritics]] in many languages. (If you want to use <code> :</code> or <code>.</code> as tokens by themselves you must precede them with a space - beware though that wiki rendering software may sometimes elide the preceding space in <nowiki><code> .</code></nowiki> contexts.) |
As an aside, note that <code>.</code> and <code>:</code> are token forming suffixes (if they immediately follow a token forming character, they are a part of the token). This usage is in analogy to the use of [[wp:Diacritic|diacritics]] in many languages. (If you want to use <code> :</code> or <code>.</code> as tokens by themselves you must precede them with a space - beware though that wiki rendering software may sometimes elide the preceding space in <nowiki><code> .</code></nowiki> contexts.) |
||
=={{header|Java}}== |
=={{header|Java}}== |
||
< |
<syntaxhighlight lang="java">import java.util.Arrays; |
||
public class Transpose{ |
public class Transpose{ |
||
public static void main(String[] args){ |
public static void main(String[] args){ |
||
Line 2,425: | Line 2,425: | ||
} |
} |
||
} |
} |
||
}</ |
}</syntaxhighlight> |
||
=={{header|JavaScript}}== |
=={{header|JavaScript}}== |
||
===ES5=== |
===ES5=== |
||
{{works with|SpiderMonkey}} for the <code>print()</code> function |
{{works with|SpiderMonkey}} for the <code>print()</code> function |
||
< |
<syntaxhighlight lang="javascript">function Matrix(ary) { |
||
this.mtx = ary |
this.mtx = ary |
||
this.height = ary.length; |
this.height = ary.length; |
||
Line 2,458: | Line 2,458: | ||
print(m); |
print(m); |
||
print(); |
print(); |
||
print(m.transpose());</ |
print(m.transpose());</syntaxhighlight> |
||
produces |
produces |
||
Line 2,474: | Line 2,474: | ||
Or, as a functional expression (rather than an imperative procedure): |
Or, as a functional expression (rather than an imperative procedure): |
||
< |
<syntaxhighlight lang="javascript"> |
||
(function () { |
(function () { |
||
'use strict'; |
'use strict'; |
||
Line 2,491: | Line 2,491: | ||
})(); |
})(); |
||
</syntaxhighlight> |
|||
</lang> |
|||
{{Out}} |
{{Out}} |
||
Line 2,499: | Line 2,499: | ||
===ES6=== |
===ES6=== |
||
< |
<syntaxhighlight lang="javascript">(() => { |
||
"use strict"; |
"use strict"; |
||
Line 2,526: | Line 2,526: | ||
// MAIN --- |
// MAIN --- |
||
return main(); |
return main(); |
||
})();</ |
})();</syntaxhighlight> |
||
{{Out}} |
{{Out}} |
||
< |
<syntaxhighlight lang="javascript">[[1,4,7],[2,5,8],[3,6,9]]</syntaxhighlight> |
||
=={{header|Joy}}== |
=={{header|Joy}}== |
||
For matrices represented as lists, there's ''transpose'', defined in seqlib like this: |
For matrices represented as lists, there's ''transpose'', defined in seqlib like this: |
||
<syntaxhighlight lang= |
<syntaxhighlight lang="joy">DEFINE transpose == [[null] [true] [[null] some] ifte] |
||
[pop []] |
[pop []] |
||
[[[first] map] [[rest] map] cleave] |
[[[first] map] [[rest] map] cleave] |
||
Line 2,543: | Line 2,543: | ||
The following definition of transpose/0 expects its input to be a non-empty array, each element of which should be an array of the same size. The result is an array that represents the transposition of the input. |
The following definition of transpose/0 expects its input to be a non-empty array, each element of which should be an array of the same size. The result is an array that represents the transposition of the input. |
||
< |
<syntaxhighlight lang="jq">def transpose: |
||
if (.[0] | length) == 0 then [] |
if (.[0] | length) == 0 then [] |
||
else [map(.[0])] + (map(.[1:]) | transpose) |
else [map(.[0])] + (map(.[1:]) | transpose) |
||
end ;</ |
end ;</syntaxhighlight> |
||
'''Examples''' |
'''Examples''' |
||
[[], []] | transpose |
[[], []] | transpose |
||
Line 2,562: | Line 2,562: | ||
First a module, shared by the Transposition, Multiplication and Exponentiation tasks. |
First a module, shared by the Transposition, Multiplication and Exponentiation tasks. |
||
< |
<syntaxhighlight lang="javascript">/* Matrix transposition, multiplication, identity, and exponentiation, in Jsish */ |
||
function Matrix(ary) { |
function Matrix(ary) { |
||
this.mtx = ary; |
this.mtx = ary; |
||
Line 2,620: | Line 2,620: | ||
}; |
}; |
||
provide('Matrix', '0.60');</ |
provide('Matrix', '0.60');</syntaxhighlight> |
||
Then a unitTest of the transposition. |
Then a unitTest of the transposition. |
||
< |
<syntaxhighlight lang="javascript">/* Matrix transposition, in Jsish */ |
||
require('Matrix'); |
require('Matrix'); |
||
Line 2,638: | Line 2,638: | ||
m.transpose() ==> { height:4, mtx:[ [ 1, 2, 3, 4, 5 ], [ 1, 4, 9, 16, 25 ], [ 1, 8, 27, 64, 125 ], [ 1, 16, 81, 256, 625 ] ], width:5 } |
m.transpose() ==> { height:4, mtx:[ [ 1, 2, 3, 4, 5 ], [ 1, 4, 9, 16, 25 ], [ 1, 8, 27, 64, 125 ], [ 1, 16, 81, 256, 625 ] ], width:5 } |
||
=!EXPECTEND!= |
=!EXPECTEND!= |
||
*/</ |
*/</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
Line 2,646: | Line 2,646: | ||
=={{header|Julia}}== |
=={{header|Julia}}== |
||
The transposition is obtained by quoting the matrix. |
The transposition is obtained by quoting the matrix. |
||
< |
<syntaxhighlight lang="julia">julia> [1 2 3 ; 4 5 6] # a 2x3 matrix |
||
2x3 Array{Int64,2}: |
2x3 Array{Int64,2}: |
||
1 2 3 |
1 2 3 |
||
Line 2,655: | Line 2,655: | ||
1 4 |
1 4 |
||
2 5 |
2 5 |
||
3 6</ |
3 6</syntaxhighlight> |
||
If you do not want change the type, convert the result back to Array{Int64,2}. |
If you do not want change the type, convert the result back to Array{Int64,2}. |
||
Line 2,661: | Line 2,661: | ||
=={{header|K}}== |
=={{header|K}}== |
||
Transpose is the monadic verb <code>+</code> |
Transpose is the monadic verb <code>+</code> |
||
< |
<syntaxhighlight lang="k"> {x^\:-1_ x}1+!:5 |
||
(1 1 1 1.0 |
(1 1 1 1.0 |
||
2 4 8 16.0 |
2 4 8 16.0 |
||
Line 2,672: | Line 2,672: | ||
1 4 9 16 25.0 |
1 4 9 16 25.0 |
||
1 8 27 64 125.0 |
1 8 27 64 125.0 |
||
1 16 81 256 625.0)</ |
1 16 81 256 625.0)</syntaxhighlight> |
||
=={{header|Klong}}== |
=={{header|Klong}}== |
||
Transpose is the monadic verb <code>+</code> |
Transpose is the monadic verb <code>+</code> |
||
< |
<syntaxhighlight lang="k"> [5 5]:^!25 |
||
[[0 1 2 3 4] |
[[0 1 2 3 4] |
||
[5 6 7 8 9] |
[5 6 7 8 9] |
||
Line 2,688: | Line 2,688: | ||
[2 7 12 17 22] |
[2 7 12 17 22] |
||
[3 8 13 18 23] |
[3 8 13 18 23] |
||
[4 9 14 19 24]]</ |
[4 9 14 19 24]]</syntaxhighlight> |
||
=={{header|Kotlin}}== |
=={{header|Kotlin}}== |
||
< |
<syntaxhighlight lang="scala">// version 1.1.3 |
||
typealias Vector = DoubleArray |
typealias Vector = DoubleArray |
||
Line 2,714: | Line 2,714: | ||
} |
} |
||
} |
} |
||
}</ |
}</syntaxhighlight> |
||
=={{header|Lang5}}== |
=={{header|Lang5}}== |
||
< |
<syntaxhighlight lang="lang5">12 iota [3 4] reshape 1 + dup . |
||
1 transpose .</ |
1 transpose .</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre>[ |
<pre>[ |
||
Line 2,733: | Line 2,733: | ||
=={{header|LFE}}== |
=={{header|LFE}}== |
||
< |
<syntaxhighlight lang="lisp"> |
||
(defun transpose (matrix) |
(defun transpose (matrix) |
||
(transpose matrix '())) |
(transpose matrix '())) |
||
Line 2,747: | Line 2,747: | ||
(tails (lists:map #'cdr/1 matrix))) |
(tails (lists:map #'cdr/1 matrix))) |
||
(transpose tails (++ acc `(,heads))))))) |
(transpose tails (++ acc `(,heads))))))) |
||
</syntaxhighlight> |
|||
</lang> |
|||
Usage in the LFE REPL: |
Usage in the LFE REPL: |
||
< |
<syntaxhighlight lang="lisp"> |
||
> (transpose '((1 2 3) |
> (transpose '((1 2 3) |
||
(4 5 6) |
(4 5 6) |
||
Line 2,760: | Line 2,760: | ||
((1 4 7 10 13 16) (2 5 8 11 14 17) (3 6 9 12 15 18)) |
((1 4 7 10 13 16) (2 5 8 11 14 17) (3 6 9 12 15 18)) |
||
> |
> |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|Liberty BASIC}}== |
=={{header|Liberty BASIC}}== |
||
There is no native matrix capability. A set of functions is available at http://www.diga.me.uk/RCMatrixFuncs.bas implementing matrices of arbitrary dimension in a string format. |
There is no native matrix capability. A set of functions is available at http://www.diga.me.uk/RCMatrixFuncs.bas implementing matrices of arbitrary dimension in a string format. |
||
< |
<syntaxhighlight lang="lb">MatrixC$ ="4, 3, 0, 0.10, 0.20, 0.30, 0.40, 0.50, 0.60, 0.70, 0.80, 0.90, 1.00, 1.10" |
||
print "Transpose of matrix" |
print "Transpose of matrix" |
||
Line 2,770: | Line 2,770: | ||
print " =" |
print " =" |
||
MatrixT$ =MatrixTranspose$( MatrixC$) |
MatrixT$ =MatrixTranspose$( MatrixC$) |
||
call DisplayMatrix MatrixT$</ |
call DisplayMatrix MatrixT$</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
Line 2,785: | Line 2,785: | ||
=={{header|Lua}}== |
=={{header|Lua}}== |
||
< |
<syntaxhighlight lang="lua">function Transpose( m ) |
||
local res = {} |
local res = {} |
||
Line 2,807: | Line 2,807: | ||
end |
end |
||
io.write( "\n" ) |
io.write( "\n" ) |
||
end</ |
end</syntaxhighlight> |
||
Using apply map list |
Using apply map list |
||
< |
<syntaxhighlight lang="lua">function map(f, a) |
||
local b = {} |
local b = {} |
||
for k,v in ipairs(a) do b[k] = f(v) end |
for k,v in ipairs(a) do b[k] = f(v) end |
||
Line 2,836: | Line 2,836: | ||
yx = apply(mapn, function(...) return {...} end, xy) |
yx = apply(mapn, function(...) return {...} end, xy) |
||
print(table.concat(map(function(a) return table.concat(a,",") end, xy), "\n"),"\n") |
print(table.concat(map(function(a) return table.concat(a,",") end, xy), "\n"),"\n") |
||
print(table.concat(map(function(a) return table.concat(a,",") end, yx), "\n"))</ |
print(table.concat(map(function(a) return table.concat(a,",") end, yx), "\n"))</syntaxhighlight> |
||
--Edit: table.getn() deprecated, using # instead |
--Edit: table.getn() deprecated, using # instead |
||
Line 2,844: | Line 2,844: | ||
The <code>Transpose</code> function in Maple's <code>LinearAlgebra</code> package computes this. The computation can also be accomplished by raising the Matrix to the <code>%T</code> power. Similarly for <code>HermitianTranspose</code> and the <code>%H</code> power. |
The <code>Transpose</code> function in Maple's <code>LinearAlgebra</code> package computes this. The computation can also be accomplished by raising the Matrix to the <code>%T</code> power. Similarly for <code>HermitianTranspose</code> and the <code>%H</code> power. |
||
<syntaxhighlight lang="maple"> |
|||
<lang Maple> |
|||
M := <<2,3>|<3,4>|<5,6>>; |
M := <<2,3>|<3,4>|<5,6>>; |
||
Line 2,851: | Line 2,851: | ||
with(LinearAlgebra): |
with(LinearAlgebra): |
||
Transpose(M); |
Transpose(M); |
||
</syntaxhighlight> |
|||
</lang> |
|||
{{out}} |
{{out}} |
||
<pre> |
<pre> |
||
Line 2,872: | Line 2,872: | ||
=={{header|Mathematica}}/{{header|Wolfram Language}}== |
=={{header|Mathematica}}/{{header|Wolfram Language}}== |
||
< |
<syntaxhighlight lang="mathematica">originalMatrix = {{1, 1, 1, 1}, |
||
{2, 4, 8, 16}, |
{2, 4, 8, 16}, |
||
{3, 9, 27, 81}, |
{3, 9, 27, 81}, |
||
{4, 16, 64, 256}, |
{4, 16, 64, 256}, |
||
{5, 25, 125, 625}} |
{5, 25, 125, 625}} |
||
transposedMatrix = Transpose[originalMatrix]</ |
transposedMatrix = Transpose[originalMatrix]</syntaxhighlight> |
||
=={{header|MATLAB}}== |
=={{header|MATLAB}}== |
||
Matlab contains two built-in methods of transposing a matrix: by using the <code>transpose()</code> function, or by using the <code>.'</code> operator. The <code>'</code> operator yields the [[conjugate transpose|complex conjugate transpose]]. |
Matlab contains two built-in methods of transposing a matrix: by using the <code>transpose()</code> function, or by using the <code>.'</code> operator. The <code>'</code> operator yields the [[conjugate transpose|complex conjugate transpose]]. |
||
< |
<syntaxhighlight lang="matlab">>> transpose([1 2;3 4]) |
||
ans = |
ans = |
||
Line 2,893: | Line 2,893: | ||
1 3 |
1 3 |
||
2 4</ |
2 4</syntaxhighlight> |
||
But, you can, obviously, do the transposition of a matrix without a built-in method, in this case, the code can be this hereafter code: |
But, you can, obviously, do the transposition of a matrix without a built-in method, in this case, the code can be this hereafter code: |
||
<syntaxhighlight lang="matlab"> |
|||
<lang Matlab> |
|||
B=size(A); %In this code, we assume that a previous matrix "A" has already been inputted. |
B=size(A); %In this code, we assume that a previous matrix "A" has already been inputted. |
||
Line 2,905: | Line 2,905: | ||
end |
end |
||
</syntaxhighlight> |
|||
</lang> |
|||
Transposing nested cells using apply map list |
Transposing nested cells using apply map list |
||
< |
<syntaxhighlight lang="matlab">xy = {{1,2,3,4},{1,2,3,4},{1,2,3,4}} |
||
yx = feval(@(x) cellfun(@(varargin)[varargin],x{:},'un',0), xy)</ |
yx = feval(@(x) cellfun(@(varargin)[varargin],x{:},'un',0), xy)</syntaxhighlight> |
||
=={{header|Maxima}}== |
=={{header|Maxima}}== |
||
< |
<syntaxhighlight lang="maxima">originalMatrix : matrix([1, 1, 1, 1], |
||
[2, 4, 8, 16], |
[2, 4, 8, 16], |
||
[3, 9, 27, 81], |
[3, 9, 27, 81], |
||
[4, 16, 64, 256], |
[4, 16, 64, 256], |
||
[5, 25, 125, 625]); |
[5, 25, 125, 625]); |
||
transposedMatrix : transpose(originalMatrix);</ |
transposedMatrix : transpose(originalMatrix);</syntaxhighlight> |
||
=={{header|MAXScript}}== |
=={{header|MAXScript}}== |
||
Uses the built in transpose() function |
Uses the built in transpose() function |
||
< |
<syntaxhighlight lang="maxscript">m = bigMatrix 5 4 |
||
for i in 1 to 5 do for j in 1 to 4 do m[i][j] = pow i j |
for i in 1 to 5 do for j in 1 to 4 do m[i][j] = pow i j |
||
m = transpose m</ |
m = transpose m</syntaxhighlight> |
||
=={{header|Nial}}== |
=={{header|Nial}}== |
||
make an array |
make an array |
||
< |
<syntaxhighlight lang="nial">|a := 2 3 reshape count 6 |
||
=1 2 3 |
=1 2 3 |
||
=4 5 6</ |
=4 5 6</syntaxhighlight> |
||
transpose it |
transpose it |
||
< |
<syntaxhighlight lang="nial">|transpose a |
||
=1 4 |
=1 4 |
||
=2 5 |
=2 5 |
||
=3 6</ |
=3 6</syntaxhighlight> |
||
=={{header|Nim}}== |
=={{header|Nim}}== |
||
For statically sized arrays: |
For statically sized arrays: |
||
< |
<syntaxhighlight lang="nim">proc transpose[X, Y; T](s: array[Y, array[X, T]]): array[X, array[Y, T]] = |
||
for i in low(X)..high(X): |
for i in low(X)..high(X): |
||
for j in low(Y)..high(Y): |
for j in low(Y)..high(Y): |
||
Line 2,950: | Line 2,950: | ||
for i in r: |
for i in r: |
||
stdout.write i, " " |
stdout.write i, " " |
||
echo ""</ |
echo ""</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre> 0 5 1 |
<pre> 0 5 1 |
||
Line 2,958: | Line 2,958: | ||
4 9 42 </pre> |
4 9 42 </pre> |
||
For dynamically sized seqs: |
For dynamically sized seqs: |
||
< |
<syntaxhighlight lang="nim">proc transpose[T](s: seq[seq[T]]): seq[seq[T]] = |
||
result = newSeq[seq[T]](s[0].len) |
result = newSeq[seq[T]](s[0].len) |
||
for i in 0 .. s[0].high: |
for i in 0 .. s[0].high: |
||
Line 2,968: | Line 2,968: | ||
@[ 5, 6, 7, 8, 9], |
@[ 5, 6, 7, 8, 9], |
||
@[ 1, 0, 0, 0, 42]] |
@[ 1, 0, 0, 0, 42]] |
||
echo transpose(a)</ |
echo transpose(a)</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre>@[@[0, 5, 1], @[1, 6, 0], @[2, 7, 0], @[3, 8, 0], @[4, 9, 42]]</pre> |
<pre>@[@[0, 5, 1], @[1, 6, 0], @[2, 7, 0], @[3, 8, 0], @[4, 9, 42]]</pre> |
||
=={{header|Objeck}}== |
=={{header|Objeck}}== |
||
< |
<syntaxhighlight lang="objeck"> |
||
bundle Default { |
bundle Default { |
||
class Transpose { |
class Transpose { |
||
Line 3,005: | Line 3,005: | ||
} |
} |
||
} |
} |
||
</syntaxhighlight> |
|||
</lang> |
|||
{{out}} |
{{out}} |
||
Line 3,019: | Line 3,019: | ||
The implementation below uses a bigarray: |
The implementation below uses a bigarray: |
||
< |
<syntaxhighlight lang="ocaml">open Bigarray |
||
let transpose b = |
let transpose b = |
||
Line 3,049: | Line 3,049: | ||
|] |
|] |
||
array2_display (Printf.printf " %d") print_newline (transpose a) ;;</ |
array2_display (Printf.printf " %d") print_newline (transpose a) ;;</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
Line 3,059: | Line 3,059: | ||
</pre> |
</pre> |
||
A version for lists: |
A version for lists: |
||
< |
<syntaxhighlight lang="ocaml">let rec transpose m = |
||
assert (m <> []); |
assert (m <> []); |
||
if List.mem [] m then |
if List.mem [] m then |
||
[] |
[] |
||
else |
else |
||
List.map List.hd m :: transpose (List.map List.tl m)</ |
List.map List.hd m :: transpose (List.map List.tl m)</syntaxhighlight> |
||
Example: |
Example: |
||
# transpose [[1;2;3;4]; |
# transpose [[1;2;3;4]; |
||
Line 3,071: | Line 3,071: | ||
=={{header|Octave}}== |
=={{header|Octave}}== |
||
< |
<syntaxhighlight lang="octave">a = [ 1, 1, 1, 1 ; |
||
2, 4, 8, 16 ; |
2, 4, 8, 16 ; |
||
3, 9, 27, 81 ; |
3, 9, 27, 81 ; |
||
Line 3,077: | Line 3,077: | ||
5, 25, 125, 625 ]; |
5, 25, 125, 625 ]; |
||
tranposed = a.'; % tranpose |
tranposed = a.'; % tranpose |
||
ctransp = a'; % conjugate transpose</ |
ctransp = a'; % conjugate transpose</syntaxhighlight> |
||
=={{header|OxygenBasic}}== |
=={{header|OxygenBasic}}== |
||
< |
<syntaxhighlight lang="oxygenbasic"> |
||
function Transpose(double *A,*B, sys nx,ny) |
function Transpose(double *A,*B, sys nx,ny) |
||
'========================================== |
'========================================== |
||
Line 3,123: | Line 3,123: | ||
Transpose A,B,5,4 |
Transpose A,B,5,4 |
||
print MatrixShow B,4,5 |
print MatrixShow B,4,5 |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|PARI/GP}}== |
=={{header|PARI/GP}}== |
||
The GP function for matrix (or vector) transpose is <code>mattranspose</code>, but it is usually invoked with a tilde: |
The GP function for matrix (or vector) transpose is <code>mattranspose</code>, but it is usually invoked with a tilde: |
||
<lang |
<syntaxhighlight lang="parigp">M~</syntaxhighlight> |
||
In PARI the function is |
In PARI the function is |
||
<lang |
<syntaxhighlight lang="c">gtrans(M)</syntaxhighlight> |
||
though <code>shallowtrans</code> is also available when deep copying is not desired. |
though <code>shallowtrans</code> is also available when deep copying is not desired. |
||
=={{header|Pascal}}== |
=={{header|Pascal}}== |
||
< |
<syntaxhighlight lang="pascal">Program Transpose; |
||
const |
const |
||
Line 3,165: | Line 3,165: | ||
writeln; |
writeln; |
||
end; |
end; |
||
end.</ |
end.</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre>% ./Transpose |
<pre>% ./Transpose |
||
Line 3,182: | Line 3,182: | ||
=={{header|Perl}}== |
=={{header|Perl}}== |
||
{{libheader|Math::Matrix}} |
{{libheader|Math::Matrix}} |
||
< |
<syntaxhighlight lang="perl">use Math::Matrix; |
||
$m = Math::Matrix->new( |
$m = Math::Matrix->new( |
||
Line 3,192: | Line 3,192: | ||
); |
); |
||
$m->transpose->print;</ |
$m->transpose->print;</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
Line 3,202: | Line 3,202: | ||
</pre> |
</pre> |
||
Manually: |
Manually: |
||
< |
<syntaxhighlight lang="perl">my @m = ( |
||
[1, 1, 1, 1], |
[1, 1, 1, 1], |
||
[2, 4, 8, 16], |
[2, 4, 8, 16], |
||
Line 3,213: | Line 3,213: | ||
foreach my $j (0..$#{$m[0]}) { |
foreach my $j (0..$#{$m[0]}) { |
||
push(@transposed, [map $_->[$j], @m]); |
push(@transposed, [map $_->[$j], @m]); |
||
}</ |
}</syntaxhighlight> |
||
=={{header|Phix}}== |
=={{header|Phix}}== |
||
<!--< |
<!--<syntaxhighlight lang="phix">(phixonline)--> |
||
<span style="color: #008080;">with</span> <span style="color: #008080;">javascript_semantics</span> |
<span style="color: #008080;">with</span> <span style="color: #008080;">javascript_semantics</span> |
||
<span style="color: #008080;">function</span> <span style="color: #000000;">matrix_transpose</span><span style="color: #0000FF;">(</span><span style="color: #004080;">sequence</span> <span style="color: #000000;">mat</span><span style="color: #0000FF;">)</span> |
<span style="color: #008080;">function</span> <span style="color: #000000;">matrix_transpose</span><span style="color: #0000FF;">(</span><span style="color: #004080;">sequence</span> <span style="color: #000000;">mat</span><span style="color: #0000FF;">)</span> |
||
Line 3,229: | Line 3,229: | ||
<span style="color: #008080;">return</span> <span style="color: #000000;">res</span> |
<span style="color: #008080;">return</span> <span style="color: #000000;">res</span> |
||
<span style="color: #008080;">end</span> <span style="color: #008080;">function</span> |
<span style="color: #008080;">end</span> <span style="color: #008080;">function</span> |
||
<!--</ |
<!--</syntaxhighlight>--> |
||
=={{header|PHP}}== |
=={{header|PHP}}== |
||
====Up to PHP version 5.6==== |
====Up to PHP version 5.6==== |
||
< |
<syntaxhighlight lang="php"> |
||
function transpose($m) { |
function transpose($m) { |
||
if (count($m) == 0) // special case: empty matrix |
if (count($m) == 0) // special case: empty matrix |
||
Line 3,243: | Line 3,243: | ||
array_unshift($m, NULL); // the original matrix is not modified because it was passed by value |
array_unshift($m, NULL); // the original matrix is not modified because it was passed by value |
||
return call_user_func_array('array_map', $m); |
return call_user_func_array('array_map', $m); |
||
}</ |
}</syntaxhighlight> |
||
====Starting with PHP 5.6==== |
====Starting with PHP 5.6==== |
||
< |
<syntaxhighlight lang="php"> |
||
function transpose($m) { |
function transpose($m) { |
||
return count($m) == 0 ? $m : (count($m) == 1 ? array_chunk($m[0], 1) : array_map(null, ...$m)); |
return count($m) == 0 ? $m : (count($m) == 1 ? array_chunk($m[0], 1) : array_map(null, ...$m)); |
||
} |
} |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|Picat}}== |
=={{header|Picat}}== |
||
Picat has a built-in function <code>transpose/1</code> (in the <code>util</code> module). |
Picat has a built-in function <code>transpose/1</code> (in the <code>util</code> module). |
||
< |
<syntaxhighlight lang="picat">import util. |
||
go => |
go => |
||
Line 3,299: | Line 3,299: | ||
end, |
end, |
||
M := M ++ [NewRow] |
M := M ++ [NewRow] |
||
end.</ |
end.</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
Line 3,343: | Line 3,343: | ||
=={{header|PicoLisp}}== |
=={{header|PicoLisp}}== |
||
< |
<syntaxhighlight lang="picolisp">(de matTrans (Mat) |
||
(apply mapcar Mat list) ) |
(apply mapcar Mat list) ) |
||
(matTrans '((1 2 3) (4 5 6)))</ |
(matTrans '((1 2 3) (4 5 6)))</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre>-> ((1 4) (2 5) (3 6))</pre> |
<pre>-> ((1 4) (2 5) (3 6))</pre> |
||
=={{header|PL/I}}== |
=={{header|PL/I}}== |
||
< |
<syntaxhighlight lang="pl/i">/* The short method: */ |
||
declare A(m, n) float, B (n,m) float defined (A(2sub, 1sub)); |
declare A(m, n) float, B (n,m) float defined (A(2sub, 1sub)); |
||
/* Any reference to B gives the transpose of matrix A. */</ |
/* Any reference to B gives the transpose of matrix A. */</syntaxhighlight> |
||
Traditional method: |
Traditional method: |
||
< |
<syntaxhighlight lang="pl/i">/* Transpose matrix A, result at B. */ |
||
transpose: procedure (a, b); |
transpose: procedure (a, b); |
||
declare (a, b) (*,*) float controlled; |
declare (a, b) (*,*) float controlled; |
||
Line 3,369: | Line 3,369: | ||
b(*,i) = a(i,*); |
b(*,i) = a(i,*); |
||
end; |
end; |
||
end transpose;</ |
end transpose;</syntaxhighlight> |
||
=={{header|Pop11}}== |
=={{header|Pop11}}== |
||
< |
<syntaxhighlight lang="pop11">define transpose(m) -> res; |
||
lvars bl = boundslist(m); |
lvars bl = boundslist(m); |
||
if length(bl) /= 4 then |
if length(bl) /= 4 then |
||
Line 3,385: | Line 3,385: | ||
endfor; |
endfor; |
||
endfor; |
endfor; |
||
enddefine;</ |
enddefine;</syntaxhighlight> |
||
=={{header|PostScript}}== |
=={{header|PostScript}}== |
||
{{libheader|initlib}} |
{{libheader|initlib}} |
||
< |
<syntaxhighlight lang="postscript">/transpose { |
||
[ exch { |
[ exch { |
||
{ {empty? exch pop} map all?} {pop exit} ift |
{ {empty? exch pop} map all?} {pop exit} ift |
||
[ exch {} {uncons {exch cons} dip exch} fold counttomark 1 roll] uncons |
[ exch {} {uncons {exch cons} dip exch} fold counttomark 1 roll] uncons |
||
} loop ] {reverse} map |
} loop ] {reverse} map |
||
}.</ |
}.</syntaxhighlight> |
||
=={{header|PowerBASIC}}== |
=={{header|PowerBASIC}}== |
||
PowerBASIC has the MAT statement to simplify Matrix Algebra calculations; in conjunction with the TRN operation the actual transposition is just a one-liner. |
PowerBASIC has the MAT statement to simplify Matrix Algebra calculations; in conjunction with the TRN operation the actual transposition is just a one-liner. |
||
< |
<syntaxhighlight lang="powerbasic">#COMPILE EXE |
||
#DIM ALL |
#DIM ALL |
||
#COMPILER PBCC 6 |
#COMPILER PBCC 6 |
||
Line 3,451: | Line 3,451: | ||
TranspositionDemo 3, 3 |
TranspositionDemo 3, 3 |
||
TranspositionDemo 3, 7 |
TranspositionDemo 3, 7 |
||
END FUNCTION</ |
END FUNCTION</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre>initial matrix: |
<pre>initial matrix: |
||
Line 3,476: | Line 3,476: | ||
=={{header|PowerShell}}== |
=={{header|PowerShell}}== |
||
===Any Matrix=== |
===Any Matrix=== |
||
<syntaxhighlight lang="powershell"> |
|||
<lang PowerShell> |
|||
function transpose($a) { |
function transpose($a) { |
||
$arr = @() |
$arr = @() |
||
Line 3,535: | Line 3,535: | ||
"transpose `$a =" |
"transpose `$a =" |
||
show (transpose $a) |
show (transpose $a) |
||
</syntaxhighlight> |
|||
</lang> |
|||
<b>Output:</b> |
<b>Output:</b> |
||
<pre> |
<pre> |
||
Line 3,582: | Line 3,582: | ||
===Square Matrix=== |
===Square Matrix=== |
||
<syntaxhighlight lang="powershell"> |
|||
<lang PowerShell> |
|||
function transpose($a) { |
function transpose($a) { |
||
if($a) { |
if($a) { |
||
Line 3,605: | Line 3,605: | ||
"" |
"" |
||
show (transpose $a) |
show (transpose $a) |
||
</syntaxhighlight> |
|||
</lang> |
|||
<b>Output:</b> |
<b>Output:</b> |
||
<pre> |
<pre> |
||
Line 3,621: | Line 3,621: | ||
In Prolog, a matrix is a list of lists. transpose/2 can be written like that. |
In Prolog, a matrix is a list of lists. transpose/2 can be written like that. |
||
{{works with|SWI-Prolog}} |
{{works with|SWI-Prolog}} |
||
< |
<syntaxhighlight lang="prolog">% transposition of a rectangular matrix |
||
% e.g. [[1,2,3,4], [5,6,7,8]] |
% e.g. [[1,2,3,4], [5,6,7,8]] |
||
% give [[1,5],[2,6],[3,7],[4,8]] |
% give [[1,5],[2,6],[3,7],[4,8]] |
||
Line 3,647: | Line 3,647: | ||
% "quick" append |
% "quick" append |
||
append_dl(X-Y, Y-Z, X-Z).</ |
append_dl(X-Y, Y-Z, X-Z).</syntaxhighlight> |
||
=={{header|PureBasic}}== |
=={{header|PureBasic}}== |
||
Matrices represented by integer arrays using rows as the first dimension and columns as the second dimension. |
Matrices represented by integer arrays using rows as the first dimension and columns as the second dimension. |
||
< |
<syntaxhighlight lang="purebasic">Procedure transposeMatrix(Array a(2), Array trans(2)) |
||
Protected rows, cols |
Protected rows, cols |
||
Line 3,702: | Line 3,702: | ||
Input() |
Input() |
||
CloseConsole() |
CloseConsole() |
||
EndIf</ |
EndIf</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre>matrix m, before: (3, 4) |
<pre>matrix m, before: (3, 4) |
||
Line 3,716: | Line 3,716: | ||
=={{header|Python}}== |
=={{header|Python}}== |
||
< |
<syntaxhighlight lang="python">m=((1, 1, 1, 1), |
||
(2, 4, 8, 16), |
(2, 4, 8, 16), |
||
(3, 9, 27, 81), |
(3, 9, 27, 81), |
||
Line 3,723: | Line 3,723: | ||
print(zip(*m)) |
print(zip(*m)) |
||
# in Python 3.x, you would do: |
# in Python 3.x, you would do: |
||
# print(list(zip(*m)))</ |
# print(list(zip(*m)))</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre> |
<pre> |
||
Line 3,741: | Line 3,741: | ||
Perhaps, for example, something like: |
Perhaps, for example, something like: |
||
< |
<syntaxhighlight lang="python"># transpose :: Matrix a -> Matrix a |
||
def transpose(m): |
def transpose(m): |
||
if m: |
if m: |
||
Line 3,781: | Line 3,781: | ||
(' of ' + type(tm[0]).__name__) if m else '' |
(' of ' + type(tm[0]).__name__) if m else '' |
||
) + ' :: ' + str(m) + ' -> ' + str(tm) |
) + ' :: ' + str(m) + ' -> ' + str(tm) |
||
)</ |
)</syntaxhighlight> |
||
{{Out}} |
{{Out}} |
||
<pre>transpose function :: (Transposition without type change): |
<pre>transpose function :: (Transposition without type change): |
||
Line 3,797: | Line 3,797: | ||
If any of the rows in a '''list of lists''' matrix are not wide enough for a full set of data for one or more of the columns, then '''zip(*xs)''' will drop all the data entirely, without warning or error message, returning no more than an empty list: |
If any of the rows in a '''list of lists''' matrix are not wide enough for a full set of data for one or more of the columns, then '''zip(*xs)''' will drop all the data entirely, without warning or error message, returning no more than an empty list: |
||
< |
<syntaxhighlight lang="python"># Uneven list of lists |
||
uls = [[10, 11], [20], [], [30, 31, 32]] |
uls = [[10, 11], [20], [], [30, 31, 32]] |
||
Line 3,804: | Line 3,804: | ||
) |
) |
||
# --> []</ |
# --> []</syntaxhighlight> |
||
At this point, short of turning to '''numpy''', we might need to write a custom function. |
At this point, short of turning to '''numpy''', we might need to write a custom function. |
||
Line 3,811: | Line 3,811: | ||
{{Works with|Python|3.7}} |
{{Works with|Python|3.7}} |
||
< |
<syntaxhighlight lang="python">'''Transposition of row sets with possible gaps''' |
||
from collections import defaultdict |
from collections import defaultdict |
||
Line 3,940: | Line 3,940: | ||
# MAIN --- |
# MAIN --- |
||
if __name__ == '__main__': |
if __name__ == '__main__': |
||
main()</ |
main()</syntaxhighlight> |
||
{{Out}} |
{{Out}} |
||
<pre>Transposition of row sets with possible gaps: |
<pre>Transposition of row sets with possible gaps: |
||
Line 3,954: | Line 3,954: | ||
=={{header|Quackery}}== |
=={{header|Quackery}}== |
||
< |
<syntaxhighlight lang="quackery"> [ ' [ [ ] ] |
||
over 0 peek size of |
over 0 peek size of |
||
[] rot |
[] rot |
||
Line 3,966: | Line 3,966: | ||
dup echo cr cr |
dup echo cr cr |
||
transpose dup echo cr cr |
transpose dup echo cr cr |
||
transpose echo cr</ |
transpose echo cr</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
Line 3,977: | Line 3,977: | ||
=={{header|R}}== |
=={{header|R}}== |
||
< |
<syntaxhighlight lang="r">b <- 1:5 |
||
m <- matrix(c(b, b^2, b^3, b^4), 5, 4) |
m <- matrix(c(b, b^2, b^3, b^4), 5, 4) |
||
print(m) |
print(m) |
||
tm <- t(m) |
tm <- t(m) |
||
print(tm)</ |
print(tm)</syntaxhighlight> |
||
=={{header|Racket}}== |
=={{header|Racket}}== |
||
< |
<syntaxhighlight lang="racket"> |
||
#lang racket |
#lang racket |
||
(require math) |
(require math) |
||
(matrix-transpose (matrix [[1 2] [3 4]])) |
(matrix-transpose (matrix [[1 2] [3 4]])) |
||
</syntaxhighlight> |
|||
</lang> |
|||
{{out}} |
{{out}} |
||
<pre> |
<pre> |
||
Line 3,999: | Line 3,999: | ||
(formerly Perl 6) |
(formerly Perl 6) |
||
{{Works with|rakudo|2018.03}} |
{{Works with|rakudo|2018.03}} |
||
<lang |
<syntaxhighlight lang="raku" line># Transposition can be done with the reduced zip meta-operator |
||
# on list-of-lists data structures |
# on list-of-lists data structures |
||
Line 4,020: | Line 4,020: | ||
} |
} |
||
say @b;</ |
say @b;</syntaxhighlight> |
||
{{output}} |
{{output}} |
||
Line 4,028: | Line 4,028: | ||
=={{header|Rascal}}== |
=={{header|Rascal}}== |
||
< |
<syntaxhighlight lang="rascal">public rel[real, real, real] matrixTranspose(rel[real x, real y, real v] matrix){ |
||
return {<y, x, v> | <x, y, v> <- matrix}; |
return {<y, x, v> | <x, y, v> <- matrix}; |
||
} |
} |
||
Line 4,037: | Line 4,037: | ||
<1.0,0.0,-51.0>, <1.0,1.0,167.0>, <1.0,2.0,24.0>, |
<1.0,0.0,-51.0>, <1.0,1.0,167.0>, <1.0,2.0,24.0>, |
||
<2.0,0.0,4.0>, <2.0,1.0,-68.0>, <2.0,2.0,-41.0> |
<2.0,0.0,4.0>, <2.0,1.0,-68.0>, <2.0,2.0,-41.0> |
||
};</ |
};</syntaxhighlight> |
||
=={{header|REXX}}== |
=={{header|REXX}}== |
||
< |
<syntaxhighlight lang="rexx">/*REXX program transposes any sized rectangular matrix, displays before & after matrices*/ |
||
@.=; @.1 = 1.02 2.03 3.04 4.05 5.06 6.07 7.08 |
@.=; @.1 = 1.02 2.03 3.04 4.05 5.06 6.07 7.08 |
||
@.2 = 111 2222 33333 444444 5555555 66666666 777777777 |
@.2 = 111 2222 33333 444444 5555555 66666666 777777777 |
||
Line 4,064: | Line 4,064: | ||
end /*c*/ |
end /*c*/ |
||
say _ /*1 line.*/ |
say _ /*1 line.*/ |
||
end /*r*/; return</ |
end /*r*/; return</syntaxhighlight> |
||
{{out|output|text= when using the default input:}} |
{{out|output|text= when using the default input:}} |
||
<pre> |
<pre> |
||
Line 4,082: | Line 4,082: | ||
=={{header|Ring}}== |
=={{header|Ring}}== |
||
< |
<syntaxhighlight lang="ring"> |
||
load "stdlib.ring" |
load "stdlib.ring" |
||
transpose = newlist(5,4) |
transpose = newlist(5,4) |
||
Line 4,093: | Line 4,093: | ||
see nl |
see nl |
||
next |
next |
||
</syntaxhighlight> |
|||
</lang> |
|||
Output: |
Output: |
||
<pre> |
<pre> |
||
Line 4,104: | Line 4,104: | ||
=={{header|RLaB}}== |
=={{header|RLaB}}== |
||
< |
<syntaxhighlight lang="rlab"> >> m = rand(3,5) |
||
0.41844289 0.476591435 0.75054022 0.226388925 0.963880314 |
0.41844289 0.476591435 0.75054022 0.226388925 0.963880314 |
||
0.91267171 0.941762397 0.464227895 0.693482786 0.203839405 |
0.91267171 0.941762397 0.464227895 0.693482786 0.203839405 |
||
Line 4,113: | Line 4,113: | ||
0.75054022 0.464227895 0.26582235 |
0.75054022 0.464227895 0.26582235 |
||
0.226388925 0.693482786 0.11557427 |
0.226388925 0.693482786 0.11557427 |
||
0.963880314 0.203839405 0.0442493069</ |
0.963880314 0.203839405 0.0442493069</syntaxhighlight> |
||
=={{header|Ruby}}== |
=={{header|Ruby}}== |
||
< |
<syntaxhighlight lang="ruby">m=[[1, 1, 1, 1], |
||
[2, 4, 8, 16], |
[2, 4, 8, 16], |
||
[3, 9, 27, 81], |
[3, 9, 27, 81], |
||
[4, 16, 64, 256], |
[4, 16, 64, 256], |
||
[5, 25,125, 625]] |
[5, 25,125, 625]] |
||
puts m.transpose</ |
puts m.transpose</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre> |
<pre> |
||
Line 4,127: | Line 4,127: | ||
</pre> |
</pre> |
||
or using 'matrix' from the standard library |
or using 'matrix' from the standard library |
||
< |
<syntaxhighlight lang="ruby">require 'matrix' |
||
m=Matrix[[1, 1, 1, 1], |
m=Matrix[[1, 1, 1, 1], |
||
Line 4,134: | Line 4,134: | ||
[4, 16, 64, 256], |
[4, 16, 64, 256], |
||
[5, 25,125, 625]] |
[5, 25,125, 625]] |
||
puts m.transpose</ |
puts m.transpose</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre> |
<pre> |
||
Line 4,140: | Line 4,140: | ||
</pre> |
</pre> |
||
or using zip: |
or using zip: |
||
< |
<syntaxhighlight lang="ruby">def transpose(m) |
||
m[0].zip(*m[1..-1]) |
m[0].zip(*m[1..-1]) |
||
end |
end |
||
p transpose([[1,2,3],[4,5,6]])</ |
p transpose([[1,2,3],[4,5,6]])</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre> |
<pre> |
||
Line 4,150: | Line 4,150: | ||
=={{header|Run BASIC}}== |
=={{header|Run BASIC}}== |
||
< |
<syntaxhighlight lang="runbasic">mtrx$ ="4, 3, 0, 0.10, 0.20, 0.30, 0.40, 0.50, 0.60, 0.70, 0.80, 0.90, 1.00, 1.10" |
||
print "Transpose of matrix" |
print "Transpose of matrix" |
||
Line 4,185: | Line 4,185: | ||
next i |
next i |
||
html "</table>" |
html "</table>" |
||
end sub</ |
end sub</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
Transpose of matrix<br><table border=2><tr align=right><td>0</td><td>0.1</td><td>0.2</td><td>0.3</td></tr><tr align=right><td>0.4</td><td>0.5</td><td>0.6</td><td>0.7</td></tr><tr align=right><td>0.8</td><td>0.9</td><td>1.0</td><td>1.1</td></tr></table> =<br /> |
Transpose of matrix<br><table border=2><tr align=right><td>0</td><td>0.1</td><td>0.2</td><td>0.3</td></tr><tr align=right><td>0.4</td><td>0.5</td><td>0.6</td><td>0.7</td></tr><tr align=right><td>0.8</td><td>0.9</td><td>1.0</td><td>1.1</td></tr></table> =<br /> |
||
Line 4,192: | Line 4,192: | ||
=={{header|Rust}}== |
=={{header|Rust}}== |
||
===version 1=== |
===version 1=== |
||
< |
<syntaxhighlight lang="rust"> |
||
struct Matrix { |
struct Matrix { |
||
dat: [[i32; 3]; 3] |
dat: [[i32; 3]; 3] |
||
Line 4,241: | Line 4,241: | ||
c.print(); |
c.print(); |
||
} |
} |
||
</syntaxhighlight> |
|||
</lang> |
|||
===version 2=== |
===version 2=== |
||
< |
<syntaxhighlight lang="rust"> |
||
fn main() { |
fn main() { |
||
let m = vec![vec![1, 2, 3], vec![4, 5, 6]]; |
let m = vec![vec![1, 2, 3], vec![4, 5, 6]]; |
||
Line 4,270: | Line 4,270: | ||
t |
t |
||
} |
} |
||
</syntaxhighlight> |
|||
</lang> |
|||
<b>Output:</b> |
<b>Output:</b> |
||
Line 4,285: | Line 4,285: | ||
=={{header|Scala}}== |
=={{header|Scala}}== |
||
< |
<syntaxhighlight lang="scala">scala> Array.tabulate(4)(i => Array.tabulate(4)(j => i*4 + j)) |
||
res12: Array[Array[Int]] = Array(Array(0, 1, 2, 3), Array(4, 5, 6, 7), Array(8, 9, 10, 11), Array(12, 13, 14, 15)) |
res12: Array[Array[Int]] = Array(Array(0, 1, 2, 3), Array(4, 5, 6, 7), Array(8, 9, 10, 11), Array(12, 13, 14, 15)) |
||
Line 4,303: | Line 4,303: | ||
1 5 9 13 |
1 5 9 13 |
||
2 6 10 14 |
2 6 10 14 |
||
3 7 11 15</ |
3 7 11 15</syntaxhighlight> |
||
=={{header|Scheme}}== |
=={{header|Scheme}}== |
||
< |
<syntaxhighlight lang="scheme">(define (transpose m) |
||
(apply map list m))</ |
(apply map list m))</syntaxhighlight> |
||
=={{header|Seed7}}== |
=={{header|Seed7}}== |
||
< |
<syntaxhighlight lang="seed7">$ include "seed7_05.s7i"; |
||
include "float.s7i"; |
include "float.s7i"; |
||
Line 4,355: | Line 4,355: | ||
writeln("After Transposition:"); |
writeln("After Transposition:"); |
||
write(transpose(testMatrix)); |
write(transpose(testMatrix)); |
||
end func;</ |
end func;</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
Line 4,372: | Line 4,372: | ||
=={{header|Sidef}}== |
=={{header|Sidef}}== |
||
< |
<syntaxhighlight lang="ruby">func transpose(matrix) { |
||
matrix[0].range.map{|i| matrix.map{_[i]}}; |
matrix[0].range.map{|i| matrix.map{_[i]}}; |
||
}; |
}; |
||
Line 4,386: | Line 4,386: | ||
transpose(m).each { |row| |
transpose(m).each { |row| |
||
"%5d" * row.len -> printlnf(row...); |
"%5d" * row.len -> printlnf(row...); |
||
}</ |
}</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre> 1 2 3 4 5 |
<pre> 1 2 3 4 5 |
||
Line 4,397: | Line 4,397: | ||
{{works with|OpenAxiom}} |
{{works with|OpenAxiom}} |
||
{{works with|Axiom}} |
{{works with|Axiom}} |
||
< |
<syntaxhighlight lang="spad">(1) -> originalMatrix := matrix [[1, 1, 1, 1],[2, 4, 8, 16], _ |
||
[3, 9, 27, 81],[4, 16, 64, 256], _ |
[3, 9, 27, 81],[4, 16, 64, 256], _ |
||
[5, 25, 125, 625]] |
[5, 25, 125, 625]] |
||
Line 4,420: | Line 4,420: | ||
| | |
| | |
||
+1 16 81 256 625+ |
+1 16 81 256 625+ |
||
Type: Matrix(Integer)</ |
Type: Matrix(Integer)</syntaxhighlight> |
||
Domain:[http://fricas.github.io/api/Matrix.html?highlight=matrix Matrix(R)] |
Domain:[http://fricas.github.io/api/Matrix.html?highlight=matrix Matrix(R)] |
||
=={{header|Sparkling}}== |
=={{header|Sparkling}}== |
||
< |
<syntaxhighlight lang="sparkling">function transpose(A) { |
||
return map(range(sizeof A), function(k, idx) { |
return map(range(sizeof A), function(k, idx) { |
||
return map(A, function(k, row) { |
return map(A, function(k, row) { |
||
Line 4,431: | Line 4,431: | ||
}); |
}); |
||
}); |
}); |
||
}</ |
}</syntaxhighlight> |
||
=={{header|Stata}}== |
=={{header|Stata}}== |
||
Line 4,437: | Line 4,437: | ||
=== Stata matrices === |
=== Stata matrices === |
||
< |
<syntaxhighlight lang="stata">. mat a=1,2,3\4,5,6 |
||
. mat b=a' |
. mat b=a' |
||
. mat list a |
. mat list a |
||
Line 4,452: | Line 4,452: | ||
c1 1 4 |
c1 1 4 |
||
c2 2 5 |
c2 2 5 |
||
c3 3 6</ |
c3 3 6</syntaxhighlight> |
||
=== Mata === |
=== Mata === |
||
< |
<syntaxhighlight lang="stata">: a=1,1i |
||
: a |
: a |
||
Line 4,475: | Line 4,475: | ||
1 | 1 | |
1 | 1 | |
||
2 | 1i | |
2 | 1i | |
||
+------+</ |
+------+</syntaxhighlight> |
||
=={{header|Swift}}== |
=={{header|Swift}}== |
||
< |
<syntaxhighlight lang="swift">@inlinable |
||
public func matrixTranspose<T>(_ matrix: [[T]]) -> [[T]] { |
public func matrixTranspose<T>(_ matrix: [[T]]) -> [[T]] { |
||
guard !matrix.isEmpty else { |
guard !matrix.isEmpty else { |
||
Line 4,528: | Line 4,528: | ||
print("Output:") |
print("Output:") |
||
printMatrix(m2)</ |
printMatrix(m2)</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
Line 4,541: | Line 4,541: | ||
=={{header|Tailspin}}== |
=={{header|Tailspin}}== |
||
< |
<syntaxhighlight lang="tailspin"> |
||
templates transpose |
templates transpose |
||
def a: $; |
def a: $; |
||
Line 4,568: | Line 4,568: | ||
' -> !OUT::write |
' -> !OUT::write |
||
$mT -> printMatrix&{w:2} -> !OUT::write |
$mT -> printMatrix&{w:2} -> !OUT::write |
||
</syntaxhighlight> |
|||
</lang> |
|||
{{out}} |
{{out}} |
||
<pre> |
<pre> |
||
Line 4,585: | Line 4,585: | ||
=={{header|Tcl}}== |
=={{header|Tcl}}== |
||
With core Tcl, representing a matrix as a list of lists: |
With core Tcl, representing a matrix as a list of lists: |
||
< |
<syntaxhighlight lang="tcl">package require Tcl 8.5 |
||
namespace path ::tcl::mathfunc |
namespace path ::tcl::mathfunc |
||
Line 4,628: | Line 4,628: | ||
set m {{1 1 1 1} {2 4 8 16} {3 9 27 81} {4 16 64 256} {5 25 125 625}} |
set m {{1 1 1 1} {2 4 8 16} {3 9 27 81} {4 16 64 256} {5 25 125 625}} |
||
print_matrix $m "%d" |
print_matrix $m "%d" |
||
print_matrix [transpose $m] "%d"</ |
print_matrix [transpose $m] "%d"</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre>1 1 1 1 |
<pre>1 1 1 1 |
||
Line 4,640: | Line 4,640: | ||
1 16 81 256 625</pre> |
1 16 81 256 625</pre> |
||
{{tcllib|struct::matrix}} |
{{tcllib|struct::matrix}} |
||
< |
<syntaxhighlight lang="tcl">package require struct::matrix |
||
struct::matrix M |
struct::matrix M |
||
M deserialize {5 4 {{1 1 1 1} {2 4 8 16} {3 9 27 81} {4 16 64 256} {5 25 125 625}}} |
M deserialize {5 4 {{1 1 1 1} {2 4 8 16} {3 9 27 81} {4 16 64 256} {5 25 125 625}}} |
||
M format 2string |
M format 2string |
||
M transpose |
M transpose |
||
M format 2string</ |
M format 2string</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre>1 1 1 1 |
<pre>1 1 1 1 |
||
Line 4,673: | Line 4,673: | ||
=={{header|True BASIC}}== |
=={{header|True BASIC}}== |
||
< |
<syntaxhighlight lang="qbasic">OPTION BASE 0 |
||
DIM matriz(3, 4) |
DIM matriz(3, 4) |
||
DATA 78, 19, 30, 12, 36 |
DATA 78, 19, 30, 12, 36 |
||
Line 4,703: | Line 4,703: | ||
PRINT |
PRINT |
||
NEXT fila |
NEXT fila |
||
END</ |
END</syntaxhighlight> |
||
=={{header|Ursala}}== |
=={{header|Ursala}}== |
||
Matrices are stored as lists of lists, and transposing them is a built in operation. |
Matrices are stored as lists of lists, and transposing them is a built in operation. |
||
< |
<syntaxhighlight lang="ursala">#cast %eLL |
||
example = |
example = |
||
Line 4,715: | Line 4,715: | ||
<1.,2.,3.,4.>, |
<1.,2.,3.,4.>, |
||
<5.,6.,7.,8.>, |
<5.,6.,7.,8.>, |
||
<9.,10.,11.,12.>></ |
<9.,10.,11.,12.>></syntaxhighlight> |
||
For a more verbose version, replace the ~&K7 operator with the standard library function |
For a more verbose version, replace the ~&K7 operator with the standard library function |
||
named transpose. |
named transpose. |
||
Line 4,728: | Line 4,728: | ||
=={{header|VBA}}== |
=={{header|VBA}}== |
||
< |
<syntaxhighlight lang="vb">Function transpose(m As Variant) As Variant |
||
transpose = WorksheetFunction.transpose(m) |
transpose = WorksheetFunction.transpose(m) |
||
End Function</ |
End Function</syntaxhighlight> |
||
=={{header|VBScript}}== |
=={{header|VBScript}}== |
||
<syntaxhighlight lang="vb"> |
|||
<lang vb> |
|||
'create and display the initial matrix |
'create and display the initial matrix |
||
WScript.StdOut.WriteLine "Initial Matrix:" |
WScript.StdOut.WriteLine "Initial Matrix:" |
||
Line 4,765: | Line 4,765: | ||
WScript.StdOut.WriteLine |
WScript.StdOut.WriteLine |
||
Next |
Next |
||
</syntaxhighlight> |
|||
</lang> |
|||
{{Out}} |
{{Out}} |
||
Line 4,790: | Line 4,790: | ||
{{works with|Visual Basic|5}} |
{{works with|Visual Basic|5}} |
||
{{works with|Visual Basic|6}} |
{{works with|Visual Basic|6}} |
||
< |
<syntaxhighlight lang="vb">Option Explicit |
||
'---------------------------------------------------------------------- |
'---------------------------------------------------------------------- |
||
Function TransposeMatrix(InitMatrix() As Long, TransposedMatrix() As Long) |
Function TransposeMatrix(InitMatrix() As Long, TransposedMatrix() As Long) |
||
Line 4,845: | Line 4,845: | ||
TranspositionDemo 3, 3 |
TranspositionDemo 3, 3 |
||
TranspositionDemo 3, 7 |
TranspositionDemo 3, 7 |
||
End Sub</ |
End Sub</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre>initial matrix: |
<pre>initial matrix: |
||
Line 4,870: | Line 4,870: | ||
=={{header|Wortel}}== |
=={{header|Wortel}}== |
||
The <code>@zipm</code> operator zips together an array of arrays, this is the same as transposition if the matrix is represented as an array of arrays. |
The <code>@zipm</code> operator zips together an array of arrays, this is the same as transposition if the matrix is represented as an array of arrays. |
||
< |
<syntaxhighlight lang="wortel">@zipm [[1 2 3] [4 5 6] [7 8 9]]</syntaxhighlight> |
||
Returns: |
Returns: |
||
<pre>[[1 4 7] [2 5 8] [3 6 9]]</pre> |
<pre>[[1 4 7] [2 5 8] [3 6 9]]</pre> |
||
Line 4,877: | Line 4,877: | ||
{{libheader|Wren-matrix}} |
{{libheader|Wren-matrix}} |
||
{{libheader|Wren-fmt}} |
{{libheader|Wren-fmt}} |
||
< |
<syntaxhighlight lang="ecmascript">import "/matrix" for Matrix |
||
import "/fmt" for Fmt |
import "/fmt" for Fmt |
||
Line 4,890: | Line 4,890: | ||
Fmt.mprint(m, 2, 0) |
Fmt.mprint(m, 2, 0) |
||
System.print("\nTransposed:\n") |
System.print("\nTransposed:\n") |
||
Fmt.mprint(m.transpose, 2, 0)</ |
Fmt.mprint(m.transpose, 2, 0)</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
Line 4,912: | Line 4,912: | ||
unusual array configuration. It can't simply reorder the elements stored |
unusual array configuration. It can't simply reorder the elements stored |
||
in the original array's memory. |
in the original array's memory. |
||
< |
<syntaxhighlight lang="xpl0">proc Transpose(M, R, C, N); \Transpose matrix M to N |
||
int M, R, C, N; \rows and columns |
int M, R, C, N; \rows and columns |
||
int I, J; |
int I, J; |
||
Line 4,939: | Line 4,939: | ||
Transpose(M, 3, 4, N); |
Transpose(M, 3, 4, N); |
||
ShowMat(N, 4, 3); |
ShowMat(N, 4, 3); |
||
]</ |
]</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
Line 4,955: | Line 4,955: | ||
=={{header|Yabasic}}== |
=={{header|Yabasic}}== |
||
{{trans|FreeBASIC}} |
{{trans|FreeBASIC}} |
||
< |
<syntaxhighlight lang="yabasic">dim matriz(4,5) |
||
dim mtranspuesta(5,4) |
dim mtranspuesta(5,4) |
||
Line 4,979: | Line 4,979: | ||
data 49,10,65,42,50 |
data 49,10,65,42,50 |
||
data 30,93,24,78,10 |
data 30,93,24,78,10 |
||
data 39,68,27,64,29</ |
data 39,68,27,64,29</syntaxhighlight> |
||
=={{header|zkl}}== |
=={{header|zkl}}== |
||
Using the GNU Scientific Library: |
Using the GNU Scientific Library: |
||
< |
<syntaxhighlight lang="zkl">var [const] GSL=Import("zklGSL"); // libGSL (GNU Scientific Library) |
||
GSL.Matrix(2,3).set(1,2,3, 4,5,6).transpose().format(5).println(); // in place |
GSL.Matrix(2,3).set(1,2,3, 4,5,6).transpose().format(5).println(); // in place |
||
println("---"); |
println("---"); |
||
GSL.Matrix(2,2).set(1,2, 3,4).transpose().format(5).println(); // in place |
GSL.Matrix(2,2).set(1,2, 3,4).transpose().format(5).println(); // in place |
||
println("---"); |
println("---"); |
||
GSL.Matrix(3,1).set(1,2,3).transpose().format(5).println(); // in place</ |
GSL.Matrix(3,1).set(1,2,3).transpose().format(5).println(); // in place</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre> |
<pre> |
||
Line 5,003: | Line 5,003: | ||
Or, using lists: |
Or, using lists: |
||
{{trans|Wortel}} |
{{trans|Wortel}} |
||
< |
<syntaxhighlight lang="zkl">fcn transpose(M){ |
||
if(M.len()==1) M[0].pump(List,List.create); // 1 row --> n columns |
if(M.len()==1) M[0].pump(List,List.create); // 1 row --> n columns |
||
else M[0].zip(M.xplode(1)); |
else M[0].zip(M.xplode(1)); |
||
}</ |
}</syntaxhighlight> |
||
The list xplode method pushes list contents on to the call stack. |
The list xplode method pushes list contents on to the call stack. |
||
< |
<syntaxhighlight lang="zkl">m:=T(T(1,2,3),T(4,5,6)); transpose(m).println(); |
||
m:=L(L(1,"a"),L(2,"b"),L(3,"c")); transpose(m).println(); |
m:=L(L(1,"a"),L(2,"b"),L(3,"c")); transpose(m).println(); |
||
transpose(L(L(1,2,3))).println(); |
transpose(L(L(1,2,3))).println(); |
||
transpose(L(L(1),L(2),L(3))).println(); |
transpose(L(L(1),L(2),L(3))).println(); |
||
transpose(L(L(1))).println();</ |
transpose(L(L(1))).println();</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre> |
<pre> |
||
Line 5,023: | Line 5,023: | ||
=={{header|zonnon}}== |
=={{header|zonnon}}== |
||
< |
<syntaxhighlight lang="zonnon"> |
||
module MatrixOps; |
module MatrixOps; |
||
type |
type |
||
Line 5,053: | Line 5,053: | ||
Transposition; |
Transposition; |
||
end MatrixOps. |
end MatrixOps. |
||
</syntaxhighlight> |
|||
</lang> |
Revision as of 22:02, 27 August 2022
![Task](http://static.miraheze.org/rosettacodewiki/thumb/b/ba/Rcode-button-task-crushed.png/64px-Rcode-button-task-crushed.png)
You are encouraged to solve this task according to the task description, using any language you may know.
Transpose an arbitrarily sized rectangular Matrix.
11l
F transpose(&matrix)
V toRet = [[0] * matrix.len] * matrix[0].len
L(row) (0 .< matrix.len)
L(col) (0 .< matrix[row].len)
toRet[col][row] = matrix[row][col]
R toRet
V m = [[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12]]
print("Original")
print(m)
print("After Transposition")
print(transpose(&m))
- Output:
Original [[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12]] After Transposition [[1, 5, 9], [2, 6, 10], [3, 7, 11], [4, 8, 12]]
360 Assembly
...
KN EQU 3
KM EQU 5
N DC AL2(KN)
M DC AL2(KM)
A DS (KN*KM)F matrix a(n,m)
B DS (KM*KN)F matrix b(m,n)
...
* b(j,i)=a(i,j)
* transposition using Horner's formula
LA R4,0 i,from 1
LA R7,KN to n
LA R6,1 step 1
LOOPI BXH R4,R6,ELOOPI do i=1 to n
LA R5,0 j,from 1
LA R9,KM to m
LA R8,1 step 1
LOOPJ BXH R5,R8,ELOOPJ do j=1 to m
LR R1,R4 i
BCTR R1,0 i-1
MH R1,M (i-1)*m
LR R2,R5 j
BCTR R2,0 j-1
AR R1,R2 r1=(i-1)*m+(j-1)
SLA R1,2 r1=((i-1)*m+(j-1))*itemlen
L R0,A(R1) r0=a(i,j)
LR R1,R5 j
BCTR R1,0 j-1
MH R1,N (j-1)*n
LR R2,R4 i
BCTR R2,0 i-1
AR R1,R2 r1=(j-1)*n+(i-1)
SLA R1,2 r1=((j-1)*n+(i-1))*itemlen
ST R0,B(R1) b(j,i)=r0
B LOOPJ next j
ELOOPJ EQU * out of loop j
B LOOPI next i
ELOOPI EQU * out of loop i
...
68000 Assembly
Transpose2DArray_B:
;INPUT:
;A0 = POINTER TO SOURCE ARRAY
;A1 = POINTER TO BACKUP AREA
; (YOU NEED THE SAME AMOUNT OF FREE SPACE AS THE SOURCE ARRAY.)
; (IT'S YOUR RESPONSIBILITY TO KNOW WHERE THAT IS.)
;D0.W = ARRAY ROW LENGTH-1
;D1.W = ARRAY COLUMN HEIGHT-1
MOVEM.L D2-D7,-(SP)
MOVE.W D0,D4 ;width - this copy is our loop counter
.outerloop:
MOVE.W D1,D7 ;height
MOVEQ.L #0,D3
MOVE.W D0,D6 ;width - this copy is used to offset the array
ADDQ.L #1,D6
.innerloop:
MOVE.B (A0,D3),(A1)+
ADD.W D6,D3
DBRA D7,.innerloop
ADDA.L #1,A0
DBRA D4,.outerloop
MOVEM.L (SP)+,D2-D7
RTS
ACL2
(defun cons-each (xs xss)
(if (or (endp xs) (endp xss))
nil
(cons (cons (first xs) (first xss))
(cons-each (rest xs) (rest xss)))))
(defun list-each (xs)
(if (endp xs)
nil
(cons (list (first xs))
(list-each (rest xs)))))
(defun transpose-list (xss)
(if (endp (rest xss))
(list-each (first xss))
(cons-each (first xss)
(transpose-list (rest xss)))))
Action!
DEFINE PTR="CARD"
TYPE Matrix=[
BYTE width,height
PTR data] ;BYTE ARRAY
PROC PrintB2(BYTE b)
IF b<10 THEN Put(32) FI
PrintB(b)
RETURN
PROC PrintMatrix(Matrix POINTER m)
BYTE i,j
BYTE ARRAY d
d=m.data
FOR j=0 TO m.height-1
DO
FOR i=0 TO m.width-1
DO
PrintB2(d(j*m.width+i)) Put(32)
OD
PutE()
OD
RETURN
PROC Create(MATRIX POINTER m BYTE w,h BYTE ARRAY a)
m.width=w
m.height=h
m.data=a
RETURN
PROC Transpose(Matrix POINTER in,out)
BYTE i,j
BYTE ARRAY din,dout
din=in.data
dout=out.data
out.width=in.height
out.height=in.width
FOR j=0 TO in.height-1
DO
FOR i=0 TO in.width-1
DO
dout(i*out.width+j)=din(j*in.width+i)
OD
OD
RETURN
PROC Main()
MATRIX in,out
BYTE ARRAY din(35),dout(35)
BYTE i
FOR i=0 TO 34
DO
din(i)=i
OD
Create(in,7,5,din)
Create(out,0,0,dout)
Transpose(in,out)
PrintE("Input:")
PrintMatrix(in)
PutE() PrintE("Transpose:")
PrintMatrix(out)
RETURN
- Output:
Screenshot from Atari 8-bit computer
Input: 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 Transpose: 0 7 14 21 28 1 8 15 22 29 2 9 16 23 30 3 10 17 24 31 4 11 18 25 32 5 12 19 26 33 6 13 20 27 34
ActionScript
In ActionScript, multi-dimensional arrays are created by making an "Array of arrays" where each element is an array.
function transpose( m:Array):Array
{
//Assume each element in m is an array. (If this were production code, use typeof to be sure)
//Each element in m is a row, so this gets the length of a row in m,
//which is the same as the number of rows in m transpose.
var mTranspose = new Array(m[0].length);
for(var i:uint = 0; i < mTranspose.length; i++)
{
//create a row
mTranspose[i] = new Array(m.length);
//set the row to the appropriate values
for(var j:uint = 0; j < mTranspose[i].length; j++)
mTranspose[i][j] = m[j][i];
}
return mTranspose;
}
var m:Array = [[1, 2, 3, 10],
[4, 5, 6, 11],
[7, 8, 9, 12]];
var M:Array = transpose(m);
for(var i:uint = 0; i < M.length; i++)
trace(M[i]);
Ada
Transpose is a function of the standard Ada library provided for matrices built upon any floating-point or complex type. The relevant packages are Ada.Numerics.Generic_Real_Arrays and Ada.Numerics.Generic_Complex_Arrays, correspondingly.
This example illustrates use of Transpose for the matrices built upon the standard type Float:
with Ada.Numerics.Real_Arrays; use Ada.Numerics.Real_Arrays;
with Ada.Text_IO; use Ada.Text_IO;
procedure Matrix_Transpose is
procedure Put (X : Real_Matrix) is
type Fixed is delta 0.01 range -500.0..500.0;
begin
for I in X'Range (1) loop
for J in X'Range (2) loop
Put (Fixed'Image (Fixed (X (I, J))));
end loop;
New_Line;
end loop;
end Put;
Matrix : constant Real_Matrix :=
( (0.0, 0.1, 0.2, 0.3),
(0.4, 0.5, 0.6, 0.7),
(0.8, 0.9, 1.0, 1.1)
);
begin
Put_Line ("Before Transposition:");
Put (Matrix);
New_Line;
Put_Line ("After Transposition:");
Put (Transpose (Matrix));
end Matrix_Transpose;
- Output:
Before Transposition: 0.00 0.10 0.20 0.30 0.40 0.50 0.60 0.70 0.80 0.90 1.00 1.10 After Transposition: 0.00 0.40 0.80 0.10 0.50 0.90 0.20 0.60 1.00 0.30 0.70 1.10
Agda
module Matrix where
open import Data.Nat
open import Data.Vec
Matrix : (A : Set) → ℕ → ℕ → Set
Matrix A m n = Vec (Vec A m) n
transpose : ∀ {A m n} → Matrix A m n → Matrix A n m
transpose [] = replicate []
transpose (xs ∷ xss) = zipWith _∷_ xs (transpose xss)
a = (1 ∷ 2 ∷ 3 ∷ []) ∷ (4 ∷ 5 ∷ 6 ∷ []) ∷ []
b = transpose a
b evaluates to the following normal form:
(1 ∷ 4 ∷ []) ∷ (2 ∷ 5 ∷ []) ∷ (3 ∷ 6 ∷ []) ∷ []
ALGOL 68
main:(
[,]REAL m=((1, 1, 1, 1),
(2, 4, 8, 16),
(3, 9, 27, 81),
(4, 16, 64, 256),
(5, 25,125, 625));
OP ZIP = ([,]REAL in)[,]REAL:(
[2 LWB in:2 UPB in,1 LWB in:1UPB in]REAL out;
FOR i FROM LWB in TO UPB in DO
out[,i]:=in[i,]
OD;
out
);
PROC pprint = ([,]REAL m)VOID:(
FORMAT real fmt = $g(-6,2)$; # width of 6, with no '+' sign, 2 decimals #
FORMAT vec fmt = $"("n(2 UPB m-1)(f(real fmt)",")f(real fmt)")"$;
FORMAT matrix fmt = $x"("n(UPB m-1)(f(vec fmt)","lxx)f(vec fmt)");"$;
# finally print the result #
printf((matrix fmt,m))
);
printf(($x"Transpose:"l$));
pprint((ZIP m))
)
- Output:
Transpose: (( 1.00, 2.00, 3.00, 4.00, 5.00), ( 1.00, 4.00, 9.00, 16.00, 25.00), ( 1.00, 8.00, 27.00, 64.00,125.00), ( 1.00, 16.00, 81.00,256.00,625.00));
Amazing Hopper
#include<hopper.h>
#proto showarraydata(_X_)
main:
.stack 12
nCols=0, nRows=0,nDims=0
A=-1,{5,11} rand array(A),mulby(10),ceil,mov(A)
{"ORIGINAL ARRAY :\n",A}
_show array data(A)
/* transpose */
TA=0,{nCols,nRows} nan array(TA)
Limit = nRows
{nRows}gthan(nCols) do{ Limit = nCols }
for (i=1, {i} lethan (Limit), ++i)
[i,i:end]get(A), [i:end,i]put(TA)
[i:end,i]get(A), [i,i:end]put(TA)
next
clear mark
{"ARRAY TRANSPOSE:\n",TA}println
_show array data(TA)
exit(0)
.locals
show array data(A)
{"\nSIZE ARRAY : "},size=0,size(A),cpy(size),
dims(size,nDims)
rows(size,nRows)
cols(size,nCols)
{"\nDIMENSION = ",nDims,"; ROWS = ",nRows,"; COLS = ",nCols,"\n"}, println
back
- Output:
ORIGINAL ARRAY : 6 6 8 3 2 6 9 3 5 3 10 6 7 10 3 9 6 5 8 8 1 10 2 3 7 10 7 9 3 7 3 8 2 10 1 3 6 9 6 1 1 5 7 7 5 9 6 1 4 3 8 4 2 10 7 SIZE ARRAY : 2 5 11 DIMENSION = 2; ROWS = 5; COLS = 11 ARRAY TRANSPOSE: 6 6 2 10 5 6 7 3 1 9 8 10 7 3 6 3 3 10 6 1 2 9 7 9 4 6 6 9 6 3 9 5 3 1 8 3 8 7 1 4 5 8 3 5 2 3 1 8 7 10 10 10 2 7 7 SIZE ARRAY : 2 11 5 DIMENSION = 2; ROWS = 11; COLS = 5
APL
If M is a matrix, ⍉M is its transpose. For example,
3 3⍴⍳10
1 2 3
4 5 6
7 8 9
⍉ 3 3⍴⍳10
1 4 7
2 5 8
3 6 9
AppleScript
We can do this iteratively, by manually setting up two nested loops, and initialising iterators and empty lists,
on run
transpose([[1, 2, 3], [4, 5, 6], [7, 8, 9], [10, 11, 12]])
--> {{1, 4, 7, 10}, {2, 5, 8, 11}, {3, 6, 9, 12}}
end run
on transpose(xss)
set lstTrans to {}
repeat with iCol from 1 to length of item 1 of xss
set lstCol to {}
repeat with iRow from 1 to length of xss
set end of lstCol to item iCol of item iRow of xss
end repeat
set end of lstTrans to lstCol
end repeat
return lstTrans
end transpose
or, if our library contains some generic basics like map(), and we use the AS script mechanism for closures, we can delegate the iterative details and write transpose() a little more declaratively, without having to reach for set, repeat, or return inside its definition.
-- TRANSPOSE -----------------------------------------------------------------
-- transpose :: [[a]] -> [[a]]
on transpose(xss)
script column
on |λ|(_, iCol)
script row
on |λ|(xs)
item iCol of xs
end |λ|
end script
map(row, xss)
end |λ|
end script
map(column, item 1 of xss)
end transpose
-- TEST ----------------------------------------------------------------------
on run
transpose([[1, 2, 3], [4, 5, 6], [7, 8, 9], [10, 11, 12]])
--> {{1, 4, 7, 10}, {2, 5, 8, 11}, {3, 6, 9, 12}}
end run
-- GENERIC FUNCTIONS ---------------------------------------------------------
-- map :: (a -> b) -> [a] -> [b]
on map(f, xs)
tell mReturn(f)
set lng to length of xs
set lst to {}
repeat with i from 1 to lng
set end of lst to |λ|(item i of xs, i, xs)
end repeat
return lst
end tell
end map
-- Lift 2nd class handler function into 1st class script wrapper
-- mReturn :: Handler -> Script
on mReturn(f)
if class of f is script then
f
else
script
property |λ| : f
end script
end if
end mReturn
- Output:
{{1, 4, 7, 10}, {2, 5, 8, 11}, {3, 6, 9, 12}}
Arturo
transpose: function [a][
X: size a
Y: size first a
result: array.of: @[Y X] 0
loop 0..X-1 'i [
loop 0..Y-1 'j [
result\[j]\[i]: a\[i]\[j]
]
]
return result
]
arr: [
[ 0 1 2 3 4 ]
[ 5 6 7 8 9 ]
[ 1 0 0 0 42 ]
]
loop arr 'row -> print row
print "-------------"
loop transpose arr 'row -> print row
- Output:
0 1 2 3 4 5 6 7 8 9 1 0 0 0 42 ------------- 0 5 1 1 6 0 2 7 0 3 8 0 4 9 42
AutoHotkey
a = a
m = 10
n = 10
Loop, 10
{
i := A_Index - 1
Loop, 10
{
j := A_Index - 1
%a%%i%%j% := i - j
}
}
before := matrix_print("a", m, n)
transpose("a", m, n)
after := matrix_print("a", m, n)
MsgBox % before . "`ntransposed:`n" . after
Return
transpose(a, m, n)
{
Local i, j, row, matrix
Loop, % m
{
i := A_Index - 1
Loop, % n
{
j := A_Index - 1
temp%i%%j% := %a%%j%%i%
}
}
Loop, % m
{
i := A_Index - 1
Loop, % n
{
j := A_Index - 1
%a%%i%%j% := temp%i%%j%
}
}
}
matrix_print(a, m, n)
{
Local i, j, row, matrix
Loop, % m
{
i := A_Index - 1
row := ""
Loop, % n
{
j := A_Index - 1
row .= %a%%i%%j% . ","
}
StringTrimRight, row, row, 1
matrix .= row . "`n"
}
Return matrix
}
Using Objects
Transpose(M){
R := []
for i, row in M
for j, col in row
R[j,i] := col
return R
}
Examples:
Matrix := [[1,2,3],[4,5,6],[7,8,9],[10,11,12]]
MsgBox % ""
. "Original Matrix :`n" Print(Matrix)
. "`nTransposed Matrix :`n" Print(Transpose(Matrix))
Print(M){
for i, row in M
for j, col in row
Res .= (A_Index=1?"":"`t") col (Mod(A_Index,M[1].MaxIndex())?"":"`n")
return Trim(Res,"`n")
}
- Output:
Original Matrix : 1 2 3 4 5 6 7 8 9 10 11 12 Transposed Matrix : 1 4 7 10 2 5 8 11 3 6 9 12
AWK
# syntax: GAWK -f MATRIX_TRANSPOSITION.AWK filename
{ if (NF > nf) {
nf = NF
}
for (i=1; i<=nf; i++) {
row[i] = row[i] $i " "
}
}
END {
for (i=1; i<=nf; i++) {
printf("%s\n",row[i])
}
exit(0)
}
input:
1 2 3 4 5 6 7 8 9 10 11 12
- Output:
1 5 9 2 6 10 3 7 11 4 8 12
Using 2D-Arrays
# Usage: GAWK -f MATRIX_TRANSPOSITION.AWK filename
{
i = NR
for (j = 1; j <= NF; j++) {
a[i,j] = $j
}
ranka1 = i
ranka2 = max(ranka2, NF)
}
END {
rankb1 = ranka2
rankb2 = ranka1
b[rankb1, rankb2] = 0
transpose_matrix(b, a)
for (i = 1; i <= rankb1; i++) {
for (j = 1; j <= rankb2; j++) {
printf("%g%c", b[i,j], j < rankb2 ? " " : "\n");
}
}
}
function transpose_matrix(target, source, key, idx) {
for (key in source) {
split(key, idx, SUBSEP)
target[idx[2], idx[1]] = source[idx[1], idx[2]]
}
}
function max(m, n) {
return m > n ? m : n
}
Input:
1 2 3 4 5 6
- Output:
1. 4. 2. 5. 3. 6.
BASIC
CLS DIM m(1 TO 5, 1 TO 4) 'any dimensions you want 'set up the values in the array FOR rows = LBOUND(m, 1) TO UBOUND(m, 1) 'LBOUND and UBOUND can take a dimension as their second argument FOR cols = LBOUND(m, 2) TO UBOUND(m, 2) m(rows, cols) = rows ^ cols 'any formula you want NEXT cols NEXT rows 'declare the new matrix DIM trans(LBOUND(m, 2) TO UBOUND(m, 2), LBOUND(m, 1) TO UBOUND(m, 1)) 'copy the values FOR rows = LBOUND(m, 1) TO UBOUND(m, 1) FOR cols = LBOUND(m, 2) TO UBOUND(m, 2) trans(cols, rows) = m(rows, cols) NEXT cols NEXT rows 'print the new matrix FOR rows = LBOUND(trans, 1) TO UBOUND(trans, 1) FOR cols = LBOUND(trans, 2) TO UBOUND(trans, 2) PRINT trans(rows, cols); NEXT cols PRINT NEXT rows
BASIC256
arraybase 1
dim matriz= {{78,19,30,12,36}, {49,10,65,42,50}, {30,93,24,78,10}, {39,68,27,64,29}}
dim mtranspuesta(matriz[,?], matriz[?,])
for fila = 1 to matriz[?,]
for columna = 1 to matriz[,?]
print matriz[fila, columna]; " ";
mtranspuesta[columna, fila] = matriz[fila, columna]
next columna
print
next fila
print
for fila = 1 to mtranspuesta[?,]
for columna = 1 to mtranspuesta[,?]
print mtranspuesta[fila, columna]; " ";
next columna
print
next fila
end
BBC BASIC
INSTALL @lib$+"ARRAYLIB"
DIM matrix(3,4), transpose(4,3)
matrix() = 78,19,30,12,36,49,10,65,42,50,30,93,24,78,10,39,68,27,64,29
PROC_transpose(matrix(), transpose())
FOR row% = 0 TO DIM(matrix(),1)
FOR col% = 0 TO DIM(matrix(),2)
PRINT ;matrix(row%,col%) " ";
NEXT
PRINT
NEXT row%
PRINT
FOR row% = 0 TO DIM(transpose(),1)
FOR col% = 0 TO DIM(transpose(),2)
PRINT ;transpose(row%,col%) " ";
NEXT
PRINT
NEXT row%
- Output:
78 19 30 12 36 49 10 65 42 50 30 93 24 78 10 39 68 27 64 29 78 49 30 39 19 10 93 68 30 65 24 27 12 42 78 64 36 50 10 29
Burlesque
blsq ) {{78 19 30 12 36}{49 10 65 42 50}{30 93 24 78 10}{39 68 27 64 29}}tpsp
78 49 30 39
19 10 93 68
30 65 24 27
12 42 78 64
36 50 10 29
C
Transpose a 2D double array.
#include <stdio.h>
void transpose(void *dest, void *src, int src_h, int src_w)
{
int i, j;
double (*d)[src_h] = dest, (*s)[src_w] = src;
for (i = 0; i < src_h; i++)
for (j = 0; j < src_w; j++)
d[j][i] = s[i][j];
}
int main()
{
int i, j;
double a[3][5] = {{ 0, 1, 2, 3, 4 },
{ 5, 6, 7, 8, 9 },
{ 1, 0, 0, 0, 42}};
double b[5][3];
transpose(b, a, 3, 5);
for (i = 0; i < 5; i++)
for (j = 0; j < 3; j++)
printf("%g%c", b[i][j], j == 2 ? '\n' : ' ');
return 0;
}
Transpose a matrix of size w x h in place with only O(1) space and without moving any element more than once. See the Wikipedia article for more information.
#include <stdio.h>
void transpose(double *m, int w, int h)
{
int start, next, i;
double tmp;
for (start = 0; start <= w * h - 1; start++) {
next = start;
i = 0;
do { i++;
next = (next % h) * w + next / h;
} while (next > start);
if (next < start || i == 1) continue;
tmp = m[next = start];
do {
i = (next % h) * w + next / h;
m[next] = (i == start) ? tmp : m[i];
next = i;
} while (next > start);
}
}
void show_matrix(double *m, int w, int h)
{
int i, j;
for (i = 0; i < h; i++) {
for (j = 0; j < w; j++)
printf("%2g ", m[i * w + j]);
putchar('\n');
}
}
int main(void)
{
int i;
double m[15];
for (i = 0; i < 15; i++) m[i] = i + 1;
puts("before transpose:");
show_matrix(m, 3, 5);
transpose(m, 3, 5);
puts("\nafter transpose:");
show_matrix(m, 5, 3);
return 0;
}
- Output:
before transpose: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 after transpose: 1 4 7 10 13 2 5 8 11 14 3 6 9 12 15
C#
using System;
using System.Text;
namespace prog
{
class MainClass
{
public static void Main (string[] args)
{
double[,] m = { {1,2,3},{4,5,6},{7,8,9} };
double[,] t = Transpose( m );
for( int i=0; i<t.GetLength(0); i++ )
{
for( int j=0; j<t.GetLength(1); j++ )
Console.Write( t[i,j] + " " );
Console.WriteLine("");
}
}
public static double[,] Transpose( double[,] m )
{
double[,] t = new double[m.GetLength(1),m.GetLength(0)];
for( int i=0; i<m.GetLength(0); i++ )
for( int j=0; j<m.GetLength(1); j++ )
t[j,i] = m[i,j];
return t;
}
}
}
C++
C++ does not have a built-in or standard-library Matrix class, so many users have rolled their own. Boost supplies one (boost::numeric::ublas::matrix<element_t> in the example below). Many users have rolled their own matrix class; a (long) code sample below shows such a class.
#include <boost/numeric/ublas/matrix.hpp>
#include <boost/numeric/ublas/io.hpp>
int main()
{
using namespace boost::numeric::ublas;
matrix<double> m(3,3);
for(int i=0; i!=m.size1(); ++i)
for(int j=0; j!=m.size2(); ++j)
m(i,j)=3*i+j;
std::cout << trans(m) << std::endl;
}
- Output:
[3,3]((0,3,6),(1,4,7),(2,5,8))
Generic solution
- main.cpp
#include <iostream>
#include "matrix.h"
#if !defined(ARRAY_SIZE)
#define ARRAY_SIZE(x) (sizeof((x)) / sizeof((x)[0]))
#endif
template<class T>
void printMatrix(const Matrix<T>& m) {
std::cout << "rows = " << m.rowNum() << " columns = " << m.colNum() << std::endl;
for (unsigned int i = 0; i < m.rowNum(); i++) {
for (unsigned int j = 0; j < m.colNum(); j++) {
std::cout << m[i][j] << " ";
}
std::cout << std::endl;
}
} /* printMatrix() */
int main() {
int am[2][3] = {
{1,2,3},
{4,5,6},
};
Matrix<int> a(ARRAY_SIZE(am), ARRAY_SIZE(am[0]), am[0], ARRAY_SIZE(am)*ARRAY_SIZE(am[0]));
try {
std::cout << "Before transposition:" << std::endl;
printMatrix(a);
std::cout << std::endl;
a.transpose();
std::cout << "After transposition:" << std::endl;
printMatrix(a);
} catch (MatrixException& e) {
std::cerr << e.message() << std::endl;
return e.errorCode();
}
} /* main() */
- matrix.h
#ifndef _MATRIX_H
#define _MATRIX_H
#include <sstream>
#include <string>
#include <vector>
#include <algorithm>
#define MATRIX_ERROR_CODE_COUNT 5
#define MATRIX_ERR_UNDEFINED "1 Undefined exception!"
#define MATRIX_ERR_WRONG_ROW_INDEX "2 The row index is out of range."
#define MATRIX_ERR_MUL_ROW_AND_COL_NOT_EQUAL "3 The row number of second matrix must be equal with the column number of first matrix!"
#define MATRIX_ERR_MUL_ROW_AND_COL_BE_GREATER_THAN_ZERO "4 The number of rows and columns must be greater than zero!"
#define MATRIX_ERR_TOO_FEW_DATA "5 Too few data in matrix."
class MatrixException {
private:
std::string message_;
int errorCode_;
public:
MatrixException(std::string message = MATRIX_ERR_UNDEFINED);
inline std::string message() {
return message_;
};
inline int errorCode() {
return errorCode_;
};
};
MatrixException::MatrixException(std::string message) {
errorCode_ = MATRIX_ERROR_CODE_COUNT + 1;
std::stringstream ss(message);
ss >> errorCode_;
if (errorCode_ < 1) {
errorCode_ = MATRIX_ERROR_CODE_COUNT + 1;
}
std::string::size_type pos = message.find(' ');
if (errorCode_ <= MATRIX_ERROR_CODE_COUNT && pos != std::string::npos) {
message_ = message.substr(pos + 1);
} else {
message_ = message + " (This an unknown and unsupported exception!)";
}
}
/**
* Generic class for matrices.
*/
template <class T>
class Matrix {
private:
std::vector<T> v; // the data of matrix
unsigned int m; // the number of rows
unsigned int n; // the number of columns
protected:
virtual void clear() {
v.clear();
m = n = 0;
}
public:
Matrix() {
clear();
}
Matrix(unsigned int, unsigned int, T* = 0, unsigned int = 0);
Matrix(unsigned int, unsigned int, const std::vector<T>&);
virtual ~Matrix() {
clear();
}
Matrix& operator=(const Matrix&);
std::vector<T> operator[](unsigned int) const;
Matrix operator*(const Matrix&);
void transpose();
inline unsigned int rowNum() const {
return m;
}
inline unsigned int colNum() const {
return n;
}
inline unsigned int size() const {
return v.size();
}
inline void add(const T& t) {
v.push_back(t);
}
};
template <class T>
Matrix<T>::Matrix(unsigned int row, unsigned int col, T* data, unsigned int dataLength) {
clear();
if (row > 0 && col > 0) {
m = row;
n = col;
unsigned int mxn = m * n;
if (dataLength && data) {
for (unsigned int i = 0; i < dataLength && i < mxn; i++) {
v.push_back(data[i]);
}
}
}
}
template <class T>
Matrix<T>::Matrix(unsigned int row, unsigned int col, const std::vector<T>& data) {
clear();
if (row > 0 && col > 0) {
m = row;
n = col;
unsigned int mxn = m * n;
if (data.size() > 0) {
for (unsigned int i = 0; i < mxn && i < data.size(); i++) {
v.push_back(data[i]);
}
}
}
}
template<class T>
Matrix<T>& Matrix<T>::operator=(const Matrix<T>& other) {
clear();
if (other.m > 0 && other.n > 0) {
m = other.m;
n = other.n;
unsigned int mxn = m * n;
for (unsigned int i = 0; i < mxn && i < other.size(); i++) {
v.push_back(other.v[i]);
}
}
return *this;
}
template<class T>
std::vector<T> Matrix<T>::operator[](unsigned int index) const {
std::vector<T> result;
if (index >= m) {
throw MatrixException(MATRIX_ERR_WRONG_ROW_INDEX);
} else if ((index + 1) * n > size()) {
throw MatrixException(MATRIX_ERR_TOO_FEW_DATA);
} else {
unsigned int begin = index * n;
unsigned int end = begin + n;
for (unsigned int i = begin; i < end; i++) {
result.push_back(v[i]);
}
}
return result;
}
template<class T>
Matrix<T> Matrix<T>::operator*(const Matrix<T>& other) {
Matrix result(m, other.n);
if (n != other.m) {
throw MatrixException(MATRIX_ERR_MUL_ROW_AND_COL_NOT_EQUAL);
} else if (m <= 0 || n <= 0 || other.n <= 0) {
throw MatrixException(MATRIX_ERR_MUL_ROW_AND_COL_BE_GREATER_THAN_ZERO);
} else if (m * n > size() || other.m * other.n > other.size()) {
throw MatrixException(MATRIX_ERR_TOO_FEW_DATA);
} else {
for (unsigned int i = 0; i < m; i++) {
for (unsigned int j = 0; j < other.n; j++) {
T temp = v[i * n] * other.v[j];
for (unsigned int k = 1; k < n; k++) {
temp += v[i * n + k] * other.v[k * other.n + j];
}
result.v.push_back(temp);
}
}
}
return result;
}
template<class T>
void Matrix<T>::transpose() {
if (m * n > size()) {
throw MatrixException(MATRIX_ERR_TOO_FEW_DATA);
} else {
std::vector<T> v2;
std::swap(v, v2);
for (unsigned int i = 0; i < n; i++) {
for (unsigned int j = 0; j < m; j++) {
v.push_back(v2[j * n + i]);
}
}
std::swap(m, n);
}
}
#endif /* _MATRIX_H */
- Output:
Before transposition: rows = 2 columns = 3 1 2 3 4 5 6 After transposition: rows = 3 columns = 2 1 4 2 5 3 6
Easy Mode
#include <iostream>
int main(){
const int l = 5;
const int w = 3;
int m1[l][w] = {{1,2,3}, {4,5,6}, {7,8,9}, {10,11,12}, {13,14,15}};
int m2[w][l];
for(int i=0; i<w; i++){
for(int x=0; x<l; x++){
m2[i][x]=m1[x][i];
}
}
// This is just output...
std::cout << "Before:";
for(int i=0; i<l; i++){
std::cout << std::endl;
for(int x=0; x<w; x++){
std::cout << m1[i][x] << " ";
}
}
std::cout << "\n\nAfter:";
for(int i=0; i<w; i++){
std::cout << std::endl;
for(int x=0; x<l; x++){
std::cout << m2[i][x] << " ";
}
}
std::cout << std::endl;
return 0;
}
- Output:
Before: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 After: 1 4 7 10 13 2 5 8 11 14 3 6 9 12 15
Clojure
(defmulti matrix-transpose
"Switch rows with columns."
class)
(defmethod matrix-transpose clojure.lang.PersistentList
[mtx]
(apply map list mtx))
(defmethod matrix-transpose clojure.lang.PersistentVector
[mtx]
(apply mapv vector mtx))
- Output:
=> (matrix-transpose [[1 2 3] [4 5 6]]) [[1 4] [2 5] [3 6]]
CoffeeScript
transpose = (matrix) ->
(t[i] for t in matrix) for i in [0...matrix[0].length]
- Output:
> transpose [[1,2,3],[4,5,6]] [[1,4],[2,5],[3,6]]
Common Lisp
If the matrix is given as a list:
(defun transpose (m)
(apply #'mapcar #'list m))
If the matrix A is given as a 2D array:
;; Transpose a mxn matrix A to a nxm matrix B=A'.
(defun mtp (A)
(let* ((m (array-dimension A 0))
(n (array-dimension A 1))
(B (make-array `(,n ,m) :initial-element 0)))
(loop for i from 0 below m do
(loop for j from 0 below n do
(setf (aref B j i)
(aref A i j))))
B))
D
Standard Version
void main() {
import std.stdio, std.range;
/*immutable*/ auto M = [[10, 11, 12, 13],
[14, 15, 16, 17],
[18, 19, 20, 21]];
writefln("%(%(%2d %)\n%)", M.transposed);
}
- Output:
10 14 18 11 15 19 12 16 20 13 17 21
Locally Procedural Style
T[][] transpose(T)(in T[][] m) pure nothrow {
auto r = new typeof(return)(m[0].length, m.length);
foreach (immutable nr, const row; m)
foreach (immutable nc, immutable c; row)
r[nc][nr] = c;
return r;
}
void main() {
import std.stdio;
immutable M = [[10, 11, 12, 13],
[14, 15, 16, 17],
[18, 19, 20, 21]];
writefln("%(%(%2d %)\n%)", M.transpose);
}
Same output.
Functional Style
import std.stdio, std.algorithm, std.range, std.functional;
auto transpose(T)(in T[][] m) pure nothrow {
return m[0].length.iota.map!(curry!(transversal, m));
}
void main() {
immutable M = [[10, 11, 12, 13],
[14, 15, 16, 17],
[18, 19, 20, 21]];
writefln("%(%(%2d %)\n%)", M.transpose);
}
Same output.
Delphi
See #Pascal;
EchoLisp
(lib 'matrix)
(define M (list->array (iota 6) 3 2))
(array-print M)
0 1
2 3
4 5
(array-print (matrix-transpose M))
0 2 4
1 3 5
EDSAC order code
In these two programs the matrix elements are stored in consecutive memory locations, in row-major order (that is, the 1st row from left to right, then the 2nd row, etc). For simplicity, matrix elements are short values, each occupying one memory location. The programs could be modified so that each element occupies two memory locations, as in the EDSAC library subroutines for vectors and matrices.
Create a new matrix
[Demo of matrix transposition. Not in place, creates a new matrix.
EDSAC, Initial Orders 2.]
..PZ [blank tape and terminator]
T 50 K [to call matrix transpose subroutine with 'G X']
P 200 F [address of matrix transpose subroutine]
T 47 K [to call matrix print subroutine with 'G M']
P 100 F [address of matrix print subroutine]
T 46 K [to call print subroutine with 'G N']
P 56 F [address of print subroutine (EDSAC library P1)]
[Subroutine to transpose a matrix of 17-bit real numbers, not in place.
Caller must ensure original and transpose don't overlap.
Parameters, all in the address field (i.e. denote n by P n F)
10F = width (number of columns)
11F = height (number of rows)
12F = start address of input matrix
13F = start address of output matrix]
E25K TX GK
[The subroutine loads elements by working down each column in turn.
Elements are stored at consecutive locations in the transposed matrix.]
A3F T31@ [set up return to caller]
A13F A33@ T14@ [initialize T order for storing transpose]
A12F A32@ U13@ [initialize A order for loading original]
T36@ [also save as A order for top of current column]
S10 F [negative of width]
[10] T35@ [initialize negative counter]
S11 F [negative of height]
[12] T34@ [initialize negative counter]
[13] AF [maunfactured order; load matrix element]
[14] TF [maunfactured order; store matrix element]
A14@ A2F T14@ [update address in T order]
A13@ A10F T13@ [update address in A order]
A34@ A2F G12@ [inner loop till finished this column]
A36@ A2F U36@ T13@ [update address for start of column]
A35@ A2F G10@ [outer loop till finished all columns]
[31] ZF [exit]
[32] AF [added to an address to make A order for that address]
[33] TF [added to an address to make T order for that address]
[34] PF [negative counter for rows]
[35] PF [negative counter for columns]
[36] AF [load order for first element in current column]
[Subroutine to print a matrix of 17-bit real numbers.
Straightforward, so given in condensed form.
Parameters (in the address field, i.e. pass n as PnF):
10F = width (number of columns)
11F = height (number of rows)
12F = start address of matrix
13F = number of decimals]
E25K TM
GKA3FT30@A13FT18@A12FA31@T14@S11FT36@S10FT37@O34@O35@TDAFT1FA16@
GN [call library subroutine P1]
PFA14@A2FT14@A37@A2FG10@O32@O33@A36@A2FG8@ZFAF@F&F!FMFPFPF
[Library subroutine P1.
Prints number in 0D to n places of decimals, where
n is specified by 'P n F' pseudo-order after subroutine call.]
E25K TN
GKA18@U17@S20@T5@H19@PFT5@VDUFOFFFSFL4FTDA5@A2FG6@EFU3FJFM1F
[Main routine]
PK T300K GK
[Constants]
[0] #F [figures shift on teleprinter]
[1] @F [carriage return]
[2] &F [line feed]
[3] P3F [number of columns (in address field)]
[4] P5F [number of rows (in address field)]
[5] P400F [address of matrix]
[6] P500F [address of transposed matrix]
[7] P2F [number of decimals when printing matrix]
[8] TF [add to address to make T order]
[9] P328F [0.0100097...., matrix elements are multiples of this]
[Variables]
[10] PF [matrix element, initialized to 0.00]
[11] PF [negative counter]
[Enter with acc = 0]
[12] O@ [set figures mode on teleprinter]
A5@ [address of matrix]
A8@ [make T order to store first elememt]
T24@ [plant in code]
H4@ N3@ L64F L32F [acc := negative number of entries]
[20] T11@ [initialize negative counter]
A10@ A9@ U10@ [increment matrix element]
[24] TF [store in matrix]
A24@ A2F T24@ [inc store address]
A11@ A2F G20@ [inc negative counter, loop till zero]
[Matrix is set up, now print it]
A3@ T10F [10F := width]
A4@ T11F [11F := height]
A5@ T12F [12F := address of matrix]
A7@ T13F [13F := number of decimals]
[39] A39@ GM [call print subroutine]
O1@ O2@ [add CR LF]
[Transpose matrix: 10F, 11F, 12F stay the same]
A6@ T13F [13F := address of transpose]
[45] A45@ GX [call transpose routine]
[Print transpose]
A10F TF A11F T10F AF T11F [swap width and height]
A13F T12F [12F := address of transpose]
A7@ T13F [13F := number of decimals]
[57] A57@ GM [call print subroutine]
O@ [figures mode, dummy to flush teleprinter buffer]
ZF [stop]
E12Z [enter at 12 (relative)]
PF [accumulator = 0 on entry]
- Output:
.01 .02 .03 .04 .05 .06 .07 .08 .09 .10 .11 .12 .13 .14 .15 .01 .04 .07 .10 .13 .02 .05 .08 .11 .14 .03 .06 .09 .12 .15
Transpose in place
That's a neat C program after the complications on Wikipedia. The way EDSAC handles arrays makes it convenient to modify the second half of the program. In C, the updated value of "next" has to be parked in another variable until m[next] (old "next") has been assigned to. In EDSAC, the instruction that assigns to m[next] can be planted before "next" is updated, and won't be affected by that update. Once the EDSAC program has been modified in this way, the code to update "next" is the same in both halves of the program and can be taken out as a subroutine.
[Transpose a matrix in place. EDSAC, Initial Orders 2.]
..PZ [blank tape and terminator]
T50K [to call matrix transpose with 'G X']
P160F [address of matrix transpose subroutine]
T47K [to call matrix print subroutine with 'G M']
P120F [address of matrix print subroutine]
T46K [to call print subroutine with 'G N']
P56F [address of print subroutine (P1 in EDSAC library)]
T48K [to call division subroutine with 'G &']
P77F [address of division subroutine]
[Subroutine to transpose a matrix of 17-bit values in place.
Translated and slightly modified from C version on Rosetta Code website.
Parameters, all in the address field (i.e. n is stored as P n F):
10F = width (number of columns, "w" in C program)
11F = height (number of rows, "h" in C program)
12F = start address of matrix]
E25K TX GK
A3F T64@ [set up return to caller]
H10F V11F L32F L64F [acc := size of matrix as width*height]
T84@ T85@ [store size; C variable start := 0]
[8] TF A85@ T86@ T87@ [set C variables, next := start, i := 0]
[12] TF A87@ A2F T87@ [i++]
A16@ G65@ [call subroutine to update "next"]
A85@ S86@ G12@ [acc := start - next, loop back if < 0]
[Skip to location 58 if acc > 0 or i = 1.
We already know that acc >= 0 and i > 0.]
S2F E58@ [subtract 1 from acc, skip if still >= 0]
S2F A87@ G58@ [acc := -2 + i, skip if < 0]
[The assignment next := start in the C program is unnecessary]
TF A86@ A12F A81@ T31@ [make and plant order to load m{next}]
[31] AF T83@ [tmp := m{next}]
[33] TF [clear acc; also added to an address to make T order for that address]
[34] A86@ A12F A33@ T54@ [make and plant order to store m{next}]
A38@ G65@ [call subroutine to update "next"]
A86@ S85@ G48@ [go to 48 if i < start]
S2F E48@ [go to 48 if i > start]
TF A82@ G52@ [make order to load tmp, and go to 52]
[48] TF A86@ A12F A81@ [make order to load m{next}]
[52] T53@ [plant order to load tmp or m{next}]
[53] AF [manufactured order; if i = start loads tmp, else loads m{next}]
[54] TF [manufactured order; stores m{next}, using old value of "next"]
A85@ S86@ G33@ [acc := start - next, loop back if < 0]
[58] TF A85@ A2F U85@ [start++]
S84@ G8@ [loop until start = size]
[64] ZF [overwritten by return to caller]
[Subroutine to execute next = (next % h) * w + next / h in C program]
[65] A3F T80@ [set up return to caller]
A86@ T4F A11F T5F [set up parameters to divide "next" by "h"]
A71@ G& [call division subroutine]
[In case anybody is following this in detail, note that "next" and "h" are
stored in the address field, so we need to shift the quotient 1 left]
H4F V10F L64F L16F A5F LD T86@ [compute RHS and store in "next"]
[80] ZF [overwritten by return to caller]
[Constants]
[81] AF [added to an address to make A order for that address]
[82] A83@ [order to load C variable "tmp"]
[Variables; integers are stored in the address field for convenience.]
[83] PF [C variable "tmp" (holds value of a matrix element)]
[84] PF [size of matrix, width*height]
[85] PF [C variable "start"]
[86] PF [C variable "next"]
[87] PF [C variable "i"]
[Subroutine to print a matrix of 17-bit real numbers.]
E25K TM
GKA3FT30@A13FT18@A12FA31@T14@S11FT36@S10FT37@O34@O35@TDAFT1FA16@
GN
PFA14@A2FT14@A37@A2FG10@O32@O33@A36@A2FG8@ZFAF@F&F!FMFPFPF
[Library subroutine P1.
Prints positive number in 0D to n places of decimals, where
n is specified by 'P n F' pseudo-order after subroutine call.]
E25K TN
GKA18@U17@S20@T5@H19@PFT5@VDUFOFFFSFL4FTDA5@A2FG6@EFU3FJFM1F
[Integer division: number at 4F, divisor at 5F
Returns remainder at 4F, quotient at 5F
Working location 0D. 37 locations.]
E25K T&
GKA3FT34@A5FUFT35@A4FRDS35@G13@T1FA35@LDE4@T1FT5FA4FS35@G22@
T4FA5FA36@T5FT1FAFS35@E34@T1FA35@RDT35@A5FLDT5FE15@EFPFPD
[Main routine]
[Given in condensed form, since it's the same as in part 1, except
that the address of the transposed matrix is not required.]
PKT250KGK#F@F&FP7FP4FP320FP2FTFP328FPFPFO@A5@A7@T23@H4@N3@L64FL32F
T10@A9@A8@U9@TFA23@A2FT23@A10@A2FG19@A3@T10FA4@T11FA5@T12FA6@T13F
A38@GMO1@O2@A42@GXA10FTFA11FT10FAFT11FA50@GMO@ZFE11ZPF
- Output:
.01 .02 .03 .04 .05 .06 .07 .08 .09 .10 .11 .12 .13 .14 .15 .16 .17 .18 .19 .20 .21 .22 .23 .24 .25 .26 .27 .28 .01 .08 .15 .22 .02 .09 .16 .23 .03 .10 .17 .24 .04 .11 .18 .25 .05 .12 .19 .26 .06 .13 .20 .27 .07 .14 .21 .28
Elixir
m = [[1, 1, 1, 1],
[2, 4, 8, 16],
[3, 9, 27, 81],
[4, 16, 64, 256],
[5, 25,125, 625]]
transpose = fn(m)-> List.zip(m) |> Enum.map(&Tuple.to_list(&1)) end
IO.inspect transpose.(m)
- Output:
[[1, 2, 3, 4, 5], [1, 4, 9, 16, 25], [1, 8, 27, 64, 125], [1, 16, 81, 256, 625]]
ELLA
Sample originally from ftp://ftp.dra.hmg.gb/pub/ella (a now dead link) - Public release.
Code for matrix transpose hardware design verification:
MAC TRANSPOSE = ([INT n][INT m]TYPE t: matrix) -> [m][n]t:
[INT i = 1..m] [INT j = 1..n] matrix[j][i].
Emacs Lisp
(require 'cl-lib)
(defun transpose (m)
(apply #'cl-mapcar #'list m))
;;test for transposition function
(transpose '((2 3 4 5) (3 5 6 9) (9 9 9 9)))
- Output:
((2 3 9) (3 5 9) (4 6 9) (5 9 9))
Erlang
A nice introduction http://langintro.com/erlang/article2/ which is much more explicit.
-module(transmatrix).
-export([trans/1,transL/1]).
% using built-ins hd = head, tl = tail
trans([[]|_]) -> [];
trans(M) ->
[ lists:map(fun hd/1, M) | transpose( lists:map(fun tl/1, M) ) ].
% Purist version
transL( [ [Elem | Rest] | List] ) ->
[ [Elem | [H || [H | _] <- List] ] |
transL( [Rest |
[ T || [_ | T] <- List ] ]
) ];
transL([ [] | List] ) -> transL(List);
transL([]) -> [].
- Output:
2> transmatrix:transL( [ [1,2,3],[4,5,6],[7,8,9] ] ). [[1,4,7],[2,5,8],[3,6,9]] 3> transmatrix:trans( [ [1,2,3],[4,5,6],[7,8,9] ] ). [[1,4,7],[2,5,8],[3,6,9]]
Euphoria
function transpose(sequence in)
sequence out
out = repeat(repeat(0,length(in)),length(in[1]))
for n = 1 to length(in) do
for m = 1 to length(in[1]) do
out[m][n] = in[n][m]
end for
end for
return out
end function
sequence m
m = {
{1,2,3,4},
{5,6,7,8},
{9,10,11,12}
}
? transpose(m)
- Output:
{ {1,5,9}, {2,6,10}, {3,7,11}, {4,8,12} }
Excel
Excel has a built-in TRANSPOSE function:
fx | =TRANSPOSE(F2#) | |||||||||
---|---|---|---|---|---|---|---|---|---|---|
A | B | C | D | E | F | G | H | I | ||
1 | Transposed | Source matrix | ||||||||
2 | 1 | 5 | 9 | 1 | 2 | 3 | 4 | |||
3 | 2 | 6 | 10 | 5 | 6 | 7 | 8 | |||
4 | 3 | 7 | 11 | 9 | 10 | 11 | 12 | |||
5 | 4 | 8 | 12 |
F#
Very straightforward solution...
let transpose (mtx : _ [,]) = Array2D.init (mtx.GetLength 1) (mtx.GetLength 0) (fun x y -> mtx.[y,x])
Factor
flip
can be used.
( scratchpad ) { { 1 2 3 } { 4 5 6 } } flip .
{ { 1 4 } { 2 5 } { 3 6 } }
Fermat
Matrix transpose is built in.
Array a[3,1]
[a]:=[(1,2,3)]
[b]:=Trans([a])
[a]
[b]
- Output:
[[ 1, ` 2, ` 3 ]] [[ 1, 2, 3 ]]
Forth
S" fsl-util.fs" REQUIRED
S" fsl/dynmem.seq" REQUIRED
: F+! ( addr -- ) ( F: r -- ) DUP F@ F+ F! ;
: FSQR ( F: r1 -- r2 ) FDUP F* ;
S" fsl/gaussj.seq" REQUIRED
5 3 float matrix a{{
1e 2e 3e 4e 5e 6e 7e 8e 9e 10e 11e 12e 13e 14e 15e 5 3 a{{ }}fput
float dmatrix b{{
a{{ 5 3 & b{{ transpose
3 5 b{{ }}fprint
Fortran
In ISO Fortran 90 or later, use the TRANSPOSE intrinsic function:
integer, parameter :: n = 3, m = 5
real, dimension(n,m) :: a = reshape( (/ (i,i=1,n*m) /), (/ n, m /) )
real, dimension(m,n) :: b
b = transpose(a)
do i = 1, n
print *, a(i,:)
end do
do j = 1, m
print *, b(j,:)
end do
In ANSI FORTRAN 77 with MIL-STD-1753 extensions or later, use nested structured DO loops:
REAL A(3,5), B(5,3)
DATA ((A(I,J),I=1,3),J=1,5) /1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15/
DO I = 1, 3
DO J = 1, 5
B(J,I) = A(I,J)
END DO
END DO
In ANSI FORTRAN 66 or later, use nested labeled DO loops:
REAL A(3,5), B(5,3)
DATA ((A(I,J),I=1,3),J=1,5) /1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15/
DO 10 I = 1, 3
DO 20 J = 1, 5
B(J,I) = A(I,J)
20 CONTINUE
10 CONTINUE
Explicit transposition via DO-loops was available from the start. Less obvious is that Fortran uses what is called "column major" order rather than "row major", which is to say that consecutive elements of the array are stored in memory with indices counting down the columns first, not along the rows. The above examples acknowledge this in the DATA statement with the ((A(row,col),row=1,3),col=1,5)
which could therefore be replaced with just A
, however one could use ((A(row,col),col=1,5),row=1,3)
instead and the DATA values could be arranged so as to appear in the same layout as one expects for a matrix. Consider
DIMENSION A(3,5),B(5,3),C(5,3)
EQUIVALENCE (A,C) !Occupy the same storage.
DATA A/
1 1, 2, 3, 4, 5,
2 6, 7, 8, 9,10,
3 11,12,13,14,15/ !Supplies values in storage order.
WRITE (6,*) "Three rows of five values:"
WRITE (6,1) A !This shows values in storage order.
WRITE (6,*) "...written as C(row,column):"
WRITE (6,2) ((C(I,J),J = 1,3),I = 1,5)
WRITE (6,*) "... written as A(row,column):"
WRITE (6,1) ((A(I,J),J = 1,5),I = 1,3)
WRITE (6,*)
WRITE (6,*) "B = Transpose(A)"
DO 10 I = 1,3
DO 10 J = 1,5
10 B(J,I) = A(I,J)
WRITE (6,*) "Five rows of three values:"
WRITE (6,2) B
WRITE (6,*) "... written as B(row,column):"
WRITE (6,2) ((B(I,J),J = 1,3),I = 1,5)
1 FORMAT (5F6.1) !Five values per line.
2 FORMAT (3F6.1) !Three values per line.
END
Output:
Three rows of five values: 1.0 2.0 3.0 4.0 5.0 6.0 7.0 8.0 9.0 10.0 11.0 12.0 13.0 14.0 15.0 ...written as C(row,column): 1.0 6.0 11.0 2.0 7.0 12.0 3.0 8.0 13.0 4.0 9.0 14.0 5.0 10.0 15.0 ... written as A(row,column): 1.0 4.0 7.0 10.0 13.0 2.0 5.0 8.0 11.0 14.0 3.0 6.0 9.0 12.0 15.0 B = Transpose(A) Five rows of three values: 1.0 4.0 7.0 10.0 13.0 2.0 5.0 8.0 11.0 14.0 3.0 6.0 9.0 12.0 15.0 ... written as B(row,column): 1.0 2.0 3.0 4.0 5.0 6.0 7.0 8.0 9.0 10.0 11.0 12.0 13.0 14.0 15.0
Thus, the first output of A replicates the layout of the DATA statement, and the output of matrix C gives its transpose. But, the values in matrix A do not appear where they would be expected to appear in terms of (row,column) as applied to the layout of the DATA statement. Only after the transposition is this so. Put another way, the ordering of array values for statements just naming the matrix (the DATA statement, and the simple write statements of A and B) is the transpose of the (row,column) expectation for a matrix. All input and output statements for matrices should thus explicitly specify the index order, even for temporary debugging, lest confusion ensue.
FreeBASIC
Dim matriz(0 To 3, 0 To 4) As Integer = {{78,19,30,12,36},_
{49,10,65,42,50},_
{30,93,24,78,10},_
{39,68,27,64,29}}
Dim As Integer mtranspuesta(Lbound(matriz, 2) To Ubound(matriz, 2), Lbound(matriz, 1) To Ubound(matriz, 1))
Dim As Integer fila, columna
For fila = Lbound(matriz,1) To Ubound(matriz,1)
For columna = Lbound(matriz,2) To Ubound(matriz,2)
mtranspuesta(columna, fila) = matriz(fila, columna)
Print ; matriz(fila,columna); " ";
Next columna
Print
Next fila
Print
For fila = Lbound(mtranspuesta,1) To Ubound(mtranspuesta,1)
For columna = Lbound(mtranspuesta,2) To Ubound(mtranspuesta,2)
Print ; mtranspuesta(fila,columna); " ";
Next columna
Print
Next fila
Sleep
- Output:
78 19 30 12 36 49 10 65 42 50 30 93 24 78 10 39 68 27 64 29 78 49 30 39 19 10 93 68 30 65 24 27 12 42 78 64 36 50 10 29
Frink
The built-in array method transpose
transposes a 2-dimensional array.
a = [[1,2,3],
[4,5,6],
[7,8,9]]
joinln[a.transpose[]]
Fōrmulæ
Fōrmulæ programs are not textual, visualization/edition of programs is done showing/manipulating structures but not text. Moreover, there can be multiple visual representations of the same program. Even though it is possible to have textual representation —i.e. XML, JSON— they are intended for storage and transfer purposes more than visualization and edition.
Programs in Fōrmulæ are created/edited online in its website, However they run on execution servers. By default remote servers are used, but they are limited in memory and processing power, since they are intended for demonstration and casual use. A local server can be downloaded and installed, it has no limitations (it runs in your own computer). Because of that, example programs can be fully visualized and edited, but some of them will not run if they require a moderate or heavy computation/memory resources, and no local server is being used.
In this page you can see the program(s) related to this task and their results.
GAP
originalMatrix := [[1, 1, 1, 1],
[2, 4, 8, 16],
[3, 9, 27, 81],
[4, 16, 64, 256],
[5, 25, 125, 625]];
transposedMatrix := TransposedMat(originalMatrix);
Go
Library gonum/mat
package main
import (
"fmt"
"gonum.org/v1/gonum/mat"
)
func main() {
m := mat.NewDense(2, 3, []float64{
1, 2, 3,
4, 5, 6,
})
fmt.Println(mat.Formatted(m))
fmt.Println()
fmt.Println(mat.Formatted(m.T()))
}
- Output:
⎡1 2 3⎤ ⎣4 5 6⎦ ⎡1 4⎤ ⎢2 5⎥ ⎣3 6⎦
Library go.matrix
package main
import (
"fmt"
mat "github.com/skelterjohn/go.matrix"
)
func main() {
m := mat.MakeDenseMatrixStacked([][]float64{
{1, 2, 3},
{4, 5, 6},
})
fmt.Println("original:")
fmt.Println(m)
m = m.Transpose()
fmt.Println("transpose:")
fmt.Println(m)
}
- Output:
original: {1, 2, 3, 4, 5, 6} transpose: {1, 4, 2, 5, 3, 6}
2D representation
Go arrays and slices are only one-dimensional. The obvious way to represent two-dimensional arrays is with a slice of slices:
package main
import "fmt"
type row []float64
type matrix []row
func main() {
m := matrix{
{1, 2, 3},
{4, 5, 6},
}
printMatrix(m)
t := transpose(m)
printMatrix(t)
}
func printMatrix(m matrix) {
for _, s := range m {
fmt.Println(s)
}
}
func transpose(m matrix) matrix {
r := make(matrix, len(m[0]))
for x, _ := range r {
r[x] = make(row, len(m))
}
for y, s := range m {
for x, e := range s {
r[x][y] = e
}
}
return r
}
- Output:
[1 2 3] [4 5 6] [1 4] [2 5] [3 6]
Flat representation
Slices of slices turn out to have disadvantages. It is possible to construct ill-formed matricies with a different number of elements on different rows, for example. They require multiple allocations, and the compiler must generate complex address calculations to index elements.
A flat element representation with a stride is almost always better.
package main
import "fmt"
type matrix struct {
ele []float64
stride int
}
// construct new matrix from slice of slices
func matrixFromRows(rows [][]float64) *matrix {
if len(rows) == 0 {
return &matrix{nil, 0}
}
m := &matrix{make([]float64, len(rows)*len(rows[0])), len(rows[0])}
for rx, row := range rows {
copy(m.ele[rx*m.stride:(rx+1)*m.stride], row)
}
return m
}
func main() {
m := matrixFromRows([][]float64{
{1, 2, 3},
{4, 5, 6},
})
m.print("original:")
m.transpose().print("transpose:")
}
func (m *matrix) print(heading string) {
if heading > "" {
fmt.Print("\n", heading, "\n")
}
for e := 0; e < len(m.ele); e += m.stride {
fmt.Println(m.ele[e : e+m.stride])
}
}
func (m *matrix) transpose() *matrix {
r := &matrix{make([]float64, len(m.ele)), len(m.ele) / m.stride}
rx := 0
for _, e := range m.ele {
r.ele[rx] = e
rx += r.stride
if rx >= len(r.ele) {
rx -= len(r.ele) - 1
}
}
return r
}
- Output:
original: [1 2 3] [4 5 6] transpose: [1 4] [2 5] [3 6]
Transpose in place
Note representation is "flat," as above, but without the fluff of constructing from rows.
package main
import "fmt"
type matrix struct {
stride int
ele []float64
}
func main() {
m := matrix{3, []float64{
1, 2, 3,
4, 5, 6,
}}
m.print("original:")
m.transposeInPlace()
m.print("transpose:")
}
func (m *matrix) print(heading string) {
if heading > "" {
fmt.Print("\n", heading, "\n")
}
for e := 0; e < len(m.ele); e += m.stride {
fmt.Println(m.ele[e : e+m.stride])
}
}
func (m *matrix) transposeInPlace() {
h := len(m.ele) / m.stride
for start := range m.ele {
next := start
i := 0
for {
i++
next = (next%h)*m.stride + next/h
if next <= start {
break
}
}
if next < start || i == 1 {
continue
}
next = start
tmp := m.ele[next]
for {
i = (next%h)*m.stride + next/h
if i == start {
m.ele[next] = tmp
} else {
m.ele[next] = m.ele[i]
}
next = i
if next <= start {
break
}
}
}
m.stride = h
}
Output same as above.
Groovy
The Groovy extensions to the List class provides a transpose method:
def matrix = [ [ 1, 2, 3, 4 ],
[ 5, 6, 7, 8 ] ]
matrix.each { println it }
println()
def transpose = matrix.transpose()
transpose.each { println it }
- Output:
[1, 2, 3, 4] [5, 6, 7, 8] [1, 5] [2, 6] [3, 7] [4, 8]
Haskell
For matrices represented as lists, there's transpose:
*Main> transpose [[1,2],[3,4],[5,6]]
[[1,3,5],[2,4,6]]
For matrices in arrays, one can use ixmap:
import Data.Array
swap (x,y) = (y,x)
transpArray :: (Ix a, Ix b) => Array (a,b) e -> Array (b,a) e
transpArray a = ixmap (swap l, swap u) swap a where
(l,u) = bounds a
Using zipWith assuming a matrix is a list of row lists:
tpose [ms] = [[m] | m <- ms]
tpose (ms:mss) = zipWith (:) ms (tpose mss)
- Output:
tpose [[1,2,3],[4,5,6],[7,8,9]] [[1,4,7],[2,5,8],[3,6,9]]
With Numeric.LinearAlgebra
import Numeric.LinearAlgebra
a :: Matrix I
a = (3><2)
[1,2
,3,4
,5,6]
main = do
print $ a
print $ tr a
- Output:
(3><2) [ 1, 2 , 3, 4 , 5, 6 ] (2><3) [ 1, 3, 5 , 2, 4, 6 ]
Haxe
class Matrix {
static function main() {
var m = [ [1, 1, 1, 1],
[2, 4, 8, 16],
[3, 9, 27, 81],
[4, 16, 64, 256],
[5, 25, 125, 625] ];
var t = [ for (i in 0...m[0].length)
[ for (j in 0...m.length) 0 ] ];
for(i in 0...m.length)
for(j in 0...m[0].length)
t[j][i] = m[i][j];
for(aa in [m, t])
for(a in aa) Sys.println(a);
}
}
- Output:
[1,1,1,1] [2,4,8,16] [3,9,27,81] [4,16,64,256] [5,25,125,625] [1,2,3,4,5] [1,4,9,16,25] [1,8,27,64,125] [1,16,81,256,625]
HicEst
REAL :: mtx(2, 4)
mtx = 1.1 * $
WRITE() mtx
SOLVE(Matrix=mtx, Transpose=mtx)
WRITE() mtx
- Output:
1.1 2.2 3.3 4.4 5.5 6.6 7.7 8.8 1.1 5.5 2.2 6.6 3.3 7.7 4.4 8.8
Hope
uses lists;
dec transpose : list (list alpha) -> list (list alpha);
--- transpose ([]::_) <= [];
--- transpose n <= map head n :: transpose (map tail n);
Icon and Unicon
- Output:
Start: 1 2 3 4 5 6 Transposed: 1 4 2 5 3 6
IDL
Standard IDL function transpose()
m=[[1,1,1,1],[2, 4, 8, 16],[3, 9,27, 81],[5, 25,125, 625]]
print,transpose(m)
Idris
Idris> transpose [[1,2],[3,4],[5,6]]
[[1, 3, 5], [2, 4, 6]] : List (List Integer)
J
Solution:
Transpose is the monadic primary verb |:
Example:
]matrix=: (^/ }:) >:i.5 NB. make and show example matrix
1 1 1 1
2 4 8 16
3 9 27 81
4 16 64 256
5 25 125 625
|: matrix
1 2 3 4 5
1 4 9 16 25
1 8 27 64 125
1 16 81 256 625
As an aside, note that .
and :
are token forming suffixes (if they immediately follow a token forming character, they are a part of the token). This usage is in analogy to the use of diacritics in many languages. (If you want to use :
or .
as tokens by themselves you must precede them with a space - beware though that wiki rendering software may sometimes elide the preceding space in <code> .</code> contexts.)
Java
import java.util.Arrays;
public class Transpose{
public static void main(String[] args){
double[][] m = {{1, 1, 1, 1},
{2, 4, 8, 16},
{3, 9, 27, 81},
{4, 16, 64, 256},
{5, 25, 125, 625}};
double[][] ans = new double[m[0].length][m.length];
for(int rows = 0; rows < m.length; rows++){
for(int cols = 0; cols < m[0].length; cols++){
ans[cols][rows] = m[rows][cols];
}
}
for(double[] i:ans){//2D arrays are arrays of arrays
System.out.println(Arrays.toString(i));
}
}
}
JavaScript
ES5
for the print()
function
function Matrix(ary) {
this.mtx = ary
this.height = ary.length;
this.width = ary[0].length;
}
Matrix.prototype.toString = function() {
var s = []
for (var i = 0; i < this.mtx.length; i++)
s.push( this.mtx[i].join(",") );
return s.join("\n");
}
// returns a new matrix
Matrix.prototype.transpose = function() {
var transposed = [];
for (var i = 0; i < this.width; i++) {
transposed[i] = [];
for (var j = 0; j < this.height; j++) {
transposed[i][j] = this.mtx[j][i];
}
}
return new Matrix(transposed);
}
var m = new Matrix([[1,1,1,1],[2,4,8,16],[3,9,27,81],[4,16,64,256],[5,25,125,625]]);
print(m);
print();
print(m.transpose());
produces
1,1,1,1 2,4,8,16 3,9,27,81 4,16,64,256 5,25,125,625 1,2,3,4,5 1,4,9,16,25 1,8,27,64,125 1,16,81,256,625
Or, as a functional expression (rather than an imperative procedure):
(function () {
'use strict';
function transpose(lst) {
return lst[0].map(function (_, iCol) {
return lst.map(function (row) {
return row[iCol];
})
});
}
return transpose(
[[1, 2, 3], [4, 5, 6], [7, 8, 9], [10, 11, 12]]
);
})();
- Output:
[[1, 4, 7, 10], [2, 5, 8, 11], [3, 6, 9, 12]]
ES6
(() => {
"use strict";
// transpose :: [[a]] -> [[a]]
const transpose = xs =>
0 < xs.length ? (
xs[0].map(
(_, iCol) => xs.map(
row => row[iCol]
)
)
) : [];
// ---------------------- TEST -----------------------
const main = () =>
JSON.stringify(
transpose([
[1, 2, 3],
[4, 5, 6],
[7, 8, 9]
])
);
// MAIN ---
return main();
})();
- Output:
[[1,4,7],[2,5,8],[3,6,9]]
Joy
For matrices represented as lists, there's transpose, defined in seqlib like this:
DEFINE transpose == [[null] [true] [[null] some] ifte]
[pop []]
[[[first] map] [[rest] map] cleave]
[cons]
linrec.
jq
Recent versions of jq include a more general "transpose" that can be used to transpose jagged matrices.
The following definition of transpose/0 expects its input to be a non-empty array, each element of which should be an array of the same size. The result is an array that represents the transposition of the input.
def transpose:
if (.[0] | length) == 0 then []
else [map(.[0])] + (map(.[1:]) | transpose)
end ;
Examples
[[], []] | transpose # => []
[[1], [3]] | transpose # => 1,3
[[1,2], [3,4]] | transpose # => [[1,3],[2,4]]
Jsish
From the Javascript Matrix entries.
First a module, shared by the Transposition, Multiplication and Exponentiation tasks.
/* Matrix transposition, multiplication, identity, and exponentiation, in Jsish */
function Matrix(ary) {
this.mtx = ary;
this.height = ary.length;
this.width = ary[0].length;
}
Matrix.prototype.toString = function() {
var s = [];
for (var i = 0; i < this.mtx.length; i++) s.push(this.mtx[i].join(","));
return s.join("\n");
};
// returns a transposed matrix
Matrix.prototype.transpose = function() {
var transposed = [];
for (var i = 0; i < this.width; i++) {
transposed[i] = [];
for (var j = 0; j < this.height; j++) transposed[i][j] = this.mtx[j][i];
}
return new Matrix(transposed);
};
// returns a matrix as the product of two others
Matrix.prototype.mult = function(other) {
if (this.width != other.height) throw "error: incompatible sizes";
var result = [];
for (var i = 0; i < this.height; i++) {
result[i] = [];
for (var j = 0; j < other.width; j++) {
var sum = 0;
for (var k = 0; k < this.width; k++) sum += this.mtx[i][k] * other.mtx[k][j];
result[i][j] = sum;
}
}
return new Matrix(result);
};
// IdentityMatrix is a "subclass" of Matrix
function IdentityMatrix(n) {
this.height = n;
this.width = n;
this.mtx = [];
for (var i = 0; i < n; i++) {
this.mtx[i] = [];
for (var j = 0; j < n; j++) this.mtx[i][j] = (i == j ? 1 : 0);
}
}
IdentityMatrix.prototype = Matrix.prototype;
// the Matrix exponentiation function
Matrix.prototype.exp = function(n) {
var result = new IdentityMatrix(this.height);
for (var i = 1; i <= n; i++) result = result.mult(this);
return result;
};
provide('Matrix', '0.60');
Then a unitTest of the transposition.
/* Matrix transposition, in Jsish */
require('Matrix');
if (Interp.conf('unitTest')) {
var m = new Matrix([[1,1,1,1],[2,4,8,16],[3,9,27,81],[4,16,64,256],[5,25,125,625]]);
; m;
; m.transpose();
}
/*
=!EXPECTSTART!=
m ==> { height:5, mtx:[ [ 1, 1, 1, 1 ], [ 2, 4, 8, 16 ], [ 3, 9, 27, 81 ], [ 4, 16, 64, 256 ], [ 5, 25, 125, 625 ] ], width:4 }
m.transpose() ==> { height:4, mtx:[ [ 1, 2, 3, 4, 5 ], [ 1, 4, 9, 16, 25 ], [ 1, 8, 27, 64, 125 ], [ 1, 16, 81, 256, 625 ] ], width:5 }
=!EXPECTEND!=
*/
- Output:
prompt$ jsish -u matrixTranspose.jsi [PASS] matrixTranspose.jsi
Julia
The transposition is obtained by quoting the matrix.
julia> [1 2 3 ; 4 5 6] # a 2x3 matrix
2x3 Array{Int64,2}:
1 2 3
4 5 6
julia> [1 2 3 ; 4 5 6]' # note the quote
3x2 LinearAlgebra.Adjoint{Int64,Array{Int64,2}}:
1 4
2 5
3 6
If you do not want change the type, convert the result back to Array{Int64,2}.
K
Transpose is the monadic verb +
{x^\:-1_ x}1+!:5
(1 1 1 1.0
2 4 8 16.0
3 9 27 81.0
4 16 64 256.0
5 25 125 625.0)
+{x^\:-1_ x}1+!:5
(1 2 3 4 5.0
1 4 9 16 25.0
1 8 27 64 125.0
1 16 81 256 625.0)
Klong
Transpose is the monadic verb +
[5 5]:^!25
[[0 1 2 3 4]
[5 6 7 8 9]
[10 11 12 13 14]
[15 16 17 18 19]
[20 21 22 23 24]]
+[5 5]:^!25
[[0 5 10 15 20]
[1 6 11 16 21]
[2 7 12 17 22]
[3 8 13 18 23]
[4 9 14 19 24]]
Kotlin
// version 1.1.3
typealias Vector = DoubleArray
typealias Matrix = Array<Vector>
fun Matrix.transpose(): Matrix {
val rows = this.size
val cols = this[0].size
val trans = Matrix(cols) { Vector(rows) }
for (i in 0 until cols) {
for (j in 0 until rows) trans[i][j] = this[j][i]
}
return trans
}
// Alternate version
typealias Matrix<T> = List<List<T>>
fun <T> Matrix<T>.transpose(): Matrix<T> {
return (0 until this[0].size).map { x ->
(this.indices).map { y ->
this[y][x]
}
}
}
Lang5
12 iota [3 4] reshape 1 + dup .
1 transpose .
- Output:
[ [ 1 2 3 4 ] [ 5 6 7 8 ] [ 9 10 11 12 ] ][ [ 1 5 9 ] [ 2 6 10 ] [ 3 7 11 ] [ 4 8 12 ] ]
LFE
(defun transpose (matrix)
(transpose matrix '()))
(defun transpose (matrix acc)
(cond
((lists:any
(lambda (x) (== x '()))
matrix)
acc)
('true
(let ((heads (lists:map #'car/1 matrix))
(tails (lists:map #'cdr/1 matrix)))
(transpose tails (++ acc `(,heads)))))))
Usage in the LFE REPL:
> (transpose '((1 2 3)
(4 5 6)
(7 8 9)
(10 11 12)
(13 14 15)
(16 17 18)))
((1 4 7 10 13 16) (2 5 8 11 14 17) (3 6 9 12 15 18))
>
Liberty BASIC
There is no native matrix capability. A set of functions is available at http://www.diga.me.uk/RCMatrixFuncs.bas implementing matrices of arbitrary dimension in a string format.
MatrixC$ ="4, 3, 0, 0.10, 0.20, 0.30, 0.40, 0.50, 0.60, 0.70, 0.80, 0.90, 1.00, 1.10"
print "Transpose of matrix"
call DisplayMatrix MatrixC$
print " ="
MatrixT$ =MatrixTranspose$( MatrixC$)
call DisplayMatrix MatrixT$
- Output:
Transpose of matrix | 0.00000 0.10000 0.20000 0.30000 | | 0.40000 0.50000 0.60000 0.70000 | | 0.80000 0.90000 1.00000 1.10000 | = | 0.00000 0.40000 0.80000 | | 0.10000 0.50000 0.90000 | | 0.20000 0.60000 1.00000 | | 0.30000 0.70000 1.10000 |
Lua
function Transpose( m )
local res = {}
for i = 1, #m[1] do
res[i] = {}
for j = 1, #m do
res[i][j] = m[j][i]
end
end
return res
end
-- a test for Transpose(m)
mat = { { 1, 2, 3 }, { 4, 5, 6 } }
erg = Transpose( mat )
for i = 1, #erg do
for j = 1, #erg[1] do
io.write( erg[i][j] )
io.write( " " )
end
io.write( "\n" )
end
Using apply map list
function map(f, a)
local b = {}
for k,v in ipairs(a) do b[k] = f(v) end
return b
end
function mapn(f, ...)
local c = {}
local k = 1
local aarg = {...}
local n = #aarg
while true do
local a = map(function(b) return b[k] end, aarg)
if #a < n then return c end
c[k] = f(unpack(a))
k = k + 1
end
end
function apply(f1, f2, a)
return f1(f2, unpack(a))
end
xy = {{1,2,3,4},{1,2,3,4},{1,2,3,4}}
yx = apply(mapn, function(...) return {...} end, xy)
print(table.concat(map(function(a) return table.concat(a,",") end, xy), "\n"),"\n")
print(table.concat(map(function(a) return table.concat(a,",") end, yx), "\n"))
--Edit: table.getn() deprecated, using # instead
Maple
The Transpose
function in Maple's LinearAlgebra
package computes this. The computation can also be accomplished by raising the Matrix to the %T
power. Similarly for HermitianTranspose
and the %H
power.
M := <<2,3>|<3,4>|<5,6>>;
M^%T;
with(LinearAlgebra):
Transpose(M);
- Output:
[2 3 5] M := [ ] [3 4 6] [2 3] [ ] [3 4] [ ] [5 6] [2 3] [ ] [3 4] [ ] [5 6]
Mathematica /Wolfram Language
originalMatrix = {{1, 1, 1, 1},
{2, 4, 8, 16},
{3, 9, 27, 81},
{4, 16, 64, 256},
{5, 25, 125, 625}}
transposedMatrix = Transpose[originalMatrix]
MATLAB
Matlab contains two built-in methods of transposing a matrix: by using the transpose()
function, or by using the .'
operator. The '
operator yields the complex conjugate transpose.
>> transpose([1 2;3 4])
ans =
1 3
2 4
>> [1 2;3 4].'
ans =
1 3
2 4
But, you can, obviously, do the transposition of a matrix without a built-in method, in this case, the code can be this hereafter code:
B=size(A); %In this code, we assume that a previous matrix "A" has already been inputted.
for j=1:B(1)
for i=1:B(2)
C(i,j)=A(j,i);
end %The transposed A-matrix should be C
end
Transposing nested cells using apply map list
xy = {{1,2,3,4},{1,2,3,4},{1,2,3,4}}
yx = feval(@(x) cellfun(@(varargin)[varargin],x{:},'un',0), xy)
Maxima
originalMatrix : matrix([1, 1, 1, 1],
[2, 4, 8, 16],
[3, 9, 27, 81],
[4, 16, 64, 256],
[5, 25, 125, 625]);
transposedMatrix : transpose(originalMatrix);
MAXScript
Uses the built in transpose() function
m = bigMatrix 5 4
for i in 1 to 5 do for j in 1 to 4 do m[i][j] = pow i j
m = transpose m
Nial
make an array
|a := 2 3 reshape count 6
=1 2 3
=4 5 6
transpose it
|transpose a
=1 4
=2 5
=3 6
Nim
For statically sized arrays:
proc transpose[X, Y; T](s: array[Y, array[X, T]]): array[X, array[Y, T]] =
for i in low(X)..high(X):
for j in low(Y)..high(Y):
result[i][j] = s[j][i]
let b = [[ 0, 1, 2, 3, 4],
[ 5, 6, 7, 8, 9],
[ 1, 0, 0, 0,42]]
let c = transpose(b)
for r in c:
for i in r:
stdout.write i, " "
echo ""
- Output:
0 5 1 1 6 0 2 7 0 3 8 0 4 9 42
For dynamically sized seqs:
proc transpose[T](s: seq[seq[T]]): seq[seq[T]] =
result = newSeq[seq[T]](s[0].len)
for i in 0 .. s[0].high:
result[i] = newSeq[T](s.len)
for j in 0 .. s.high:
result[i][j] = s[j][i]
let a = @[@[ 0, 1, 2, 3, 4],
@[ 5, 6, 7, 8, 9],
@[ 1, 0, 0, 0, 42]]
echo transpose(a)
- Output:
@[@[0, 5, 1], @[1, 6, 0], @[2, 7, 0], @[3, 8, 0], @[4, 9, 42]]
Objeck
bundle Default {
class Transpose {
function : Main(args : String[]) ~ Nil {
input := [[1, 1, 1, 1]
[2, 4, 8, 16]
[3, 9, 27, 81]
[4, 16, 64, 256]
[5, 25, 125, 625]];
dim := input->Size();
output := Int->New[dim[0],dim[1]];
for(i := 0; i < dim[0]; i+=1;) {
for(j := 0; j < dim[1]; j+=1;) {
output[i,j] := input[i,j];
};
};
Print(output);
}
function : Print(matrix : Int[,]) ~ Nil {
dim := matrix->Size();
for(i := 0; i < dim[0]; i+=1;) {
for(j := 0; j < dim[1]; j+=1;) {
IO.Console->Print(matrix[i,j])->Print('\t');
};
'\n'->Print();
};
}
}
}
- Output:
1 2 3 4 5 1 4 9 16 25 1 8 27 64 125 1 16 81 256 625
OCaml
Matrices can be represented in OCaml as a type 'a array array, or using the module Bigarray. The implementation below uses a bigarray:
open Bigarray
let transpose b =
let dim1 = Array2.dim1 b
and dim2 = Array2.dim2 b in
let kind = Array2.kind b
and layout = Array2.layout b in
let b' = Array2.create kind layout dim2 dim1 in
for i=0 to pred dim1 do
for j=0 to pred dim2 do
b'.{j,i} <- b.{i,j}
done;
done;
(b')
;;
let array2_display print newline b =
for i=0 to Array2.dim1 b - 1 do
for j=0 to Array2.dim2 b - 1 do
print b.{i,j}
done;
newline();
done;
;;
let a = Array2.of_array int c_layout [|
[| 1; 2; 3; 4 |];
[| 5; 6; 7; 8 |];
|]
array2_display (Printf.printf " %d") print_newline (transpose a) ;;
- Output:
1 5 2 6 3 7 4 8
A version for lists:
let rec transpose m =
assert (m <> []);
if List.mem [] m then
[]
else
List.map List.hd m :: transpose (List.map List.tl m)
Example:
# transpose [[1;2;3;4]; [5;6;7;8]];; - : int list list = [[1; 5]; [2; 6]; [3; 7]; [4; 8]]
Octave
a = [ 1, 1, 1, 1 ;
2, 4, 8, 16 ;
3, 9, 27, 81 ;
4, 16, 64, 256 ;
5, 25, 125, 625 ];
tranposed = a.'; % tranpose
ctransp = a'; % conjugate transpose
OxygenBasic
function Transpose(double *A,*B, sys nx,ny)
'==========================================
sys x,y
indexbase 0
for x=0 to <nx
for y=0 to <ny
B[y*nx+x]=A[x*ny+y]
next
next
end function
function MatrixShow(double*A, sys nx,ny) as string
'=================================================
sys x,y
indexbase 0
string pr="",tab=chr(9),cr=chr(13)+chr(10)
for y=0 to <ny
for x=0 to <nx
pr+=tab A[x*ny+y]
next
pr+=cr
next
return pr
end function
'====
'DEMO
'====
double A[5*4],B[4*5]
'columns x
'rows y
A <= 'y minor, x major
11,12,13,14,15,
21,22,23,24,25,
31,32,33,34,35,
41,42,43,44,45
print MatrixShow A,5,4
Transpose A,B,5,4
print MatrixShow B,4,5
PARI/GP
The GP function for matrix (or vector) transpose is mattranspose
, but it is usually invoked with a tilde:
M~
In PARI the function is
gtrans(M)
though shallowtrans
is also available when deep copying is not desired.
Pascal
Program Transpose;
const
A: array[1..3,1..5] of integer = (( 1, 2, 3, 4, 5),
( 6, 7, 8, 9, 10),
(11, 12, 13, 14, 15)
);
var
B: array[1..5,1..3] of integer;
i, j: integer;
begin
for i := low(A) to high(A) do
for j := low(A[1]) to high(A[1]) do
B[j,i] := A[i,j];
writeln ('A:');
for i := low(A) to high(A) do
begin
for j := low(A[1]) to high(A[1]) do
write (A[i,j]:3);
writeln;
end;
writeln ('B:');
for i := low(B) to high(B) do
begin
for j := low(B[1]) to high(B[1]) do
write (B[i,j]:3);
writeln;
end;
end.
- Output:
% ./Transpose A: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 B: 1 6 11 2 7 12 3 8 13 4 9 14 5 10 15
Perl
use Math::Matrix;
$m = Math::Matrix->new(
[1, 1, 1, 1],
[2, 4, 8, 16],
[3, 9, 27, 81],
[4, 16, 64, 256],
[5, 25, 125, 625],
);
$m->transpose->print;
- Output:
1.00000 2.00000 3.00000 4.00000 5.00000 1.00000 4.00000 9.00000 16.00000 25.00000 1.00000 8.00000 27.00000 64.00000 125.00000 1.00000 16.00000 81.00000 256.00000 625.00000
Manually:
my @m = (
[1, 1, 1, 1],
[2, 4, 8, 16],
[3, 9, 27, 81],
[4, 16, 64, 256],
[5, 25, 125, 625],
);
my @transposed;
foreach my $j (0..$#{$m[0]}) {
push(@transposed, [map $_->[$j], @m]);
}
Phix
with javascript_semantics function matrix_transpose(sequence mat) integer rows = length(mat), cols = length(mat[1]) sequence res = repeat(repeat(0,rows),cols) for r=1 to rows do for c=1 to cols do res[c][r] = mat[r][c] end for end for return res end function
PHP
Up to PHP version 5.6
function transpose($m) {
if (count($m) == 0) // special case: empty matrix
return array();
else if (count($m) == 1) // special case: row matrix
return array_chunk($m[0], 1);
// array_map(NULL, m[0], m[1], ..)
array_unshift($m, NULL); // the original matrix is not modified because it was passed by value
return call_user_func_array('array_map', $m);
}
Starting with PHP 5.6
function transpose($m) {
return count($m) == 0 ? $m : (count($m) == 1 ? array_chunk($m[0], 1) : array_map(null, ...$m));
}
Picat
Picat has a built-in function transpose/1
(in the util
module).
import util.
go =>
M = [[0.0, 0.1, 0.2, 0.3],
[0.4, 0.5, 0.6, 0.7],
[0.8, 0.9, 1.0, 1.1]],
print_matrix(M),
M2 = [[a,b,c,d,e],
[f,g,h,i,j],
[k,l,m,n,o],
[p,q,r,s,t],
[u,v,w,z,y]],
print_matrix(M2),
M3 = make_matrix(1..24,8),
print_matrix(M3),
nl.
%
% Print original matrix and its transpose
%
print_matrix(M) =>
println("Matrix:"),
foreach(Row in M) println(Row) end,
println("\nTransposed:"),
foreach(Row in M.transpose()) println(Row) end,
nl.
%
% Make a matrix of list L with Rows rows
% (and L.length div Rows columns)
%
make_matrix(L,Rows) = M =>
M = [],
Cols = L.length div Rows,
foreach(I in 1..Rows)
NewRow = new_list(Cols),
foreach(J in 1..Cols)
NewRow[J] := L[ (I-1)*Cols + J]
end,
M := M ++ [NewRow]
end.
- Output:
Matrix: [0.0,0.1,0.2,0.3] [0.4,0.5,0.6,0.7] [0.8,0.9,1.0,1.1] Transposed: [0.0,0.4,0.8] [0.1,0.5,0.9] [0.2,0.6,1.0] [0.3,0.7,1.1] Matrix: abcde fghij klmno pqrst uvwzy Transposed: afkpu bglqv chmrw dinsz ejoty Matrix: [1,2,3] [4,5,6] [7,8,9] [10,11,12] [13,14,15] [16,17,18] [19,20,21] [22,23,24] Transposed: [1,4,7,10,13,16,19,22] [2,5,8,11,14,17,20,23] [3,6,9,12,15,18,21,24]
PicoLisp
(de matTrans (Mat)
(apply mapcar Mat list) )
(matTrans '((1 2 3) (4 5 6)))
- Output:
-> ((1 4) (2 5) (3 6))
PL/I
/* The short method: */
declare A(m, n) float, B (n,m) float defined (A(2sub, 1sub));
/* Any reference to B gives the transpose of matrix A. */
Traditional method:
/* Transpose matrix A, result at B. */
transpose: procedure (a, b);
declare (a, b) (*,*) float controlled;
declare (m, n) fixed binary;
if allocation(b) > 0 then free b;
m = hbound(a,1); n = hbound(a,2);
allocate b(n,m);
do i = 1 to m;
b(*,i) = a(i,*);
end;
end transpose;
Pop11
define transpose(m) -> res;
lvars bl = boundslist(m);
if length(bl) /= 4 then
throw([need_2d_array ^a])
endif;
lvars i, i0 = bl(1), i1 = bl(2);
lvars j, j0 = bl(3), j1 = bl(4);
newarray([^j0 ^j1 ^i0 ^i1], 0) -> res;
for i from i0 to i1 do
for j from j0 to j1 do
m(i, j) -> res(j, i);
endfor;
endfor;
enddefine;
PostScript
/transpose {
[ exch {
{ {empty? exch pop} map all?} {pop exit} ift
[ exch {} {uncons {exch cons} dip exch} fold counttomark 1 roll] uncons
} loop ] {reverse} map
}.
PowerBASIC
PowerBASIC has the MAT statement to simplify Matrix Algebra calculations; in conjunction with the TRN operation the actual transposition is just a one-liner.
#COMPILE EXE
#DIM ALL
#COMPILER PBCC 6
'----------------------------------------------------------------------
SUB TransposeMatrix(InitMatrix() AS DWORD, TransposedMatrix() AS DWORD)
LOCAL l1, l2, u1, u2 AS LONG
l1 = LBOUND(InitMatrix, 1)
l2 = LBOUND(InitMatrix, 2)
u1 = UBOUND(InitMatrix, 1)
u2 = UBOUND(InitMatrix, 2)
REDIM TransposedMatrix(l2 TO u2, l1 TO u1)
MAT TransposedMatrix() = TRN(InitMatrix())
END SUB
'----------------------------------------------------------------------
SUB PrintMatrix(a() AS DWORD)
LOCAL l1, l2, u1, u2, r, c AS LONG
LOCAL s AS STRING * 8
l1 = LBOUND(a(), 1)
l2 = LBOUND(a(), 2)
u1 = UBOUND(a(), 1)
u2 = UBOUND(a(), 2)
FOR r = l1 TO u1
FOR c = l2 TO u2
RSET s = STR$(a(r, c))
CON.PRINT s;
NEXT c
CON.PRINT
NEXT r
END SUB
'----------------------------------------------------------------------
SUB TranspositionDemo(BYVAL DimSize1 AS DWORD, BYVAL DimSize2 AS DWORD)
LOCAL r, c, cc AS DWORD
LOCAL a() AS DWORD
LOCAL b() AS DWORD
cc = DimSize2
DECR DimSize1
DECR DimSize2
REDIM a(0 TO DimSize1, 0 TO DimSize2)
FOR r = 0 TO DimSize1
FOR c = 0 TO DimSize2
a(r, c)= (cc * r) + c + 1
NEXT c
NEXT r
CON.PRINT "initial matrix:"
PrintMatrix a()
TransposeMatrix a(), b()
CON.PRINT "transposed matrix:"
PrintMatrix b()
END SUB
'----------------------------------------------------------------------
FUNCTION PBMAIN () AS LONG
TranspositionDemo 3, 3
TranspositionDemo 3, 7
END FUNCTION
- Output:
initial matrix: 1 2 3 4 5 6 7 8 9 transposed matrix: 1 4 7 2 5 8 3 6 9 initial matrix: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 transposed matrix: 1 8 15 2 9 16 3 10 17 4 11 18 5 12 19 6 13 20 7 14 21
PowerShell
Any Matrix
function transpose($a) {
$arr = @()
if($a) {
$n = $a.count - 1
if(0 -lt $n) {
$m = ($a | foreach {$_.count} | measure-object -Minimum).Minimum - 1
if( 0 -le $m) {
if (0 -lt $m) {
$arr =@(0)*($m+1)
foreach($i in 0..$m) {
$arr[$i] = foreach($j in 0..$n) {@($a[$j][$i])}
}
} else {$arr = foreach($row in $a) {$row[0]}}
}
} else {$arr = $a}
}
$arr
}
function show($a) {
if($a) {
0..($a.Count - 1) | foreach{ if($a[$_]){"$($a[$_])"}else{""} }
}
}
$a = @(@(2, 0, 7, 8),@(3, 5, 9, 1),@(4, 1, 6, 3))
"`$a ="
show $a
""
"transpose `$a ="
show (transpose $a)
""
$a = @(1)
"`$a ="
show $a
""
"transpose `$a ="
show (transpose $a)
""
"`$a ="
$a = @(1,2,3)
show $a
""
"transpose `$a ="
"$(transpose $a)"
""
"`$a ="
$a = @(@(4,7,8),@(1),@(2,3))
show $a
""
"transpose `$a ="
"$(transpose $a)"
""
"`$a ="
$a = @(@(4,7,8),@(1,5,9,0),@(2,3))
show $a
""
"transpose `$a ="
show (transpose $a)
Output:
$a = 2 0 7 8 3 5 9 1 4 1 6 3 transpose $a = 2 3 4 0 5 1 7 9 6 8 1 3 $a = 1 transpose $a = 1 $a = 1 2 3 transpose $a = 1 2 3 $a = 4 7 8 1 2 3 transpose $a = 4 1 2 $a = 4 7 8 1 5 9 0 2 3 transpose $a = 4 1 2 7 5 3
Square Matrix
function transpose($a) {
if($a) {
$n = $a.Count - 1
foreach($i in 0..$n) {
$j = 0
while($j -lt $i) {
$a[$i][$j], $a[$j][$i] = $a[$j][$i], $a[$i][$j]
$j++
}
}
}
$a
}
function show($a) {
if($a) {
0..($a.Count - 1) | foreach{ if($a[$_]){"$($a[$_])"}else{""} }
}
}
$a = @(@(2, 4, 7),@(3, 5, 9),@(4, 1, 6))
show $a
""
show (transpose $a)
Output:
2 4 7 3 5 9 4 1 6 2 3 4 4 5 1 7 9 6
Prolog
Predicate transpose/2 exists in libray clpfd of SWI-Prolog.
In Prolog, a matrix is a list of lists. transpose/2 can be written like that.
% transposition of a rectangular matrix
% e.g. [[1,2,3,4], [5,6,7,8]]
% give [[1,5],[2,6],[3,7],[4,8]]
transpose(In, Out) :-
In = [H | T],
maplist(initdl, H, L),
work(T, In, Out).
% we use the difference list to make "quick" appends (one inference)
initdl(V, [V | X] - X).
work(Lst, [H], Out) :-
maplist(my_append_last, Lst, H, Out).
work(Lst, [H | T], Out) :-
maplist(my_append, Lst, H, Lst1),
work(Lst1, T, Out).
my_append(X-Y, C, X1-Y1) :-
append_dl(X-Y, [C | U]- U, X1-Y1).
my_append_last(X-Y, C, X1) :-
append_dl(X-Y, [C | U]- U, X1-[]).
% "quick" append
append_dl(X-Y, Y-Z, X-Z).
PureBasic
Matrices represented by integer arrays using rows as the first dimension and columns as the second dimension.
Procedure transposeMatrix(Array a(2), Array trans(2))
Protected rows, cols
Protected ar = ArraySize(a(), 1) ;rows in original matrix
Protected ac = ArraySize(a(), 2) ;cols in original matrix
;size the matrix receiving the transposition
Dim trans(ac, ar)
;copy the values
For rows = 0 To ar
For cols = 0 To ac
trans(cols, rows) = a(rows, cols)
Next
Next
EndProcedure
Procedure displayMatrix(Array a(2), text.s = "")
Protected i, j
Protected cols = ArraySize(a(), 2), rows = ArraySize(a(), 1)
PrintN(text + ": (" + Str(rows + 1) + ", " + Str(cols + 1) + ")")
For i = 0 To rows
For j = 0 To cols
Print(LSet(Str(a(i, j)), 4, " "))
Next
PrintN("")
Next
PrintN("")
EndProcedure
;setup a matrix of arbitrary size
Dim m(random(5), random(5))
Define rows, cols
;fill matrix with 'random' data
For rows = 0 To ArraySize(m(),1) ;ArraySize() can take a dimension as its second argument
For cols = 0 To ArraySize(m(), 2)
m(rows, cols) = random(10) - 10
Next
Next
Dim t(0,0) ;this will be resized during transposition
If OpenConsole()
displayMatrix(m(), "matrix before transposition")
transposeMatrix(m(), t())
displayMatrix(t(), "matrix after transposition")
Print(#CRLF$ + #CRLF$ + "Press ENTER to exit")
Input()
CloseConsole()
EndIf
- Output:
matrix m, before: (3, 4) -4 -9 -7 -9 -3 -6 -4 -6 -1 -2 0 -6 matrix m after transposition: (4, 3) -4 -3 -1 -9 -6 -2 -7 -4 0 -9 -6 -6
Python
m=((1, 1, 1, 1),
(2, 4, 8, 16),
(3, 9, 27, 81),
(4, 16, 64, 256),
(5, 25,125, 625))
print(zip(*m))
# in Python 3.x, you would do:
# print(list(zip(*m)))
- Output:
[(1, 2, 3, 4, 5), (1, 4, 9, 16, 25), (1, 8, 27, 64, 125), (1, 16, 81, 256, 625)]
Note, however, that zip, while very useful, doesn't give us a simple type-safe transposition – it is actually a 'transpose + coerce' function rather than a pure transpose function; polymorphic in its inputs, but not in its outputs.
zip accepts matrices in any of the 4 permutations of (outer lists or tuples) * (inner lists or tuples), but it always and only returns a zip of tuples, losing any information about what the input type was.
For type-specific transpositions without coercion (and for a richer set of matrix types, and higher level of efficiency – transpositions are an inherently expensive operation) we can turn to numpy.
Meanwhile, for the four basic types of Python matrices (the cartesian product of (inner type, container type) * (tuple, list), the simplest (though not necessarily most efficient) approach (in the absence of numpy) may be to write a type-sensitive wrapper, which retains and restores the type information that zip discards.
Perhaps, for example, something like:
# transpose :: Matrix a -> Matrix a
def transpose(m):
if m:
inner = type(m[0])
z = zip(*m)
return (type(m))(
map(inner, z) if tuple != inner else z
)
else:
return m
if __name__ == '__main__':
# TRANSPOSING FOUR BASIC TYPES OF PYTHON MATRIX
# Cartesian product of (Outer, Inner) with (List, Tuple)
# Matrix any = Tuple of Tuples of any type
tts = ((1, 2, 3), (4, 5, 6), (7, 8, 9))
# Matrix any = Tuple of Lists of any type
tls = ([1, 2, 3], [4, 5, 6], [7, 8, 9])
emptyTuple = ()
# Matrix any = List of Lists of any type
lls = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
# Matrix any = List of Tuples of any type
lts = [(1, 2, 3), (4, 5, 6), (7, 8, 9)]
emptyList = []
print('transpose function :: (Transposition without type change):\n')
for m in [emptyTuple, tts, tls, emptyList, lls, lts]:
tm = transpose(m)
print (
type(tm).__name__ + (
(' of ' + type(tm[0]).__name__) if m else ''
) + ' :: ' + str(m) + ' -> ' + str(tm)
)
- Output:
transpose function :: (Transposition without type change): tuple :: () -> () tuple of tuple :: ((1, 2, 3), (4, 5, 6), (7, 8, 9)) -> ((1, 4, 7), (2, 5, 8), (3, 6, 9)) tuple of list :: ([1, 2, 3], [4, 5, 6], [7, 8, 9]) -> ([1, 4, 7], [2, 5, 8], [3, 6, 9]) list :: [] -> [] list of list :: [[1, 2, 3], [4, 5, 6], [7, 8, 9]] -> [[1, 4, 7], [2, 5, 8], [3, 6, 9]] list of tuple :: [(1, 2, 3), (4, 5, 6), (7, 8, 9)] -> [(1, 4, 7), (2, 5, 8), (3, 6, 9)]
Even with its type amnesia fixed, zip may still not be the instrument to reach for when it's possible that our matrices may contain gaps.
If any of the rows in a list of lists matrix are not wide enough for a full set of data for one or more of the columns, then zip(*xs) will drop all the data entirely, without warning or error message, returning no more than an empty list:
# Uneven list of lists
uls = [[10, 11], [20], [], [30, 31, 32]]
print (
list(zip(*uls))
)
# --> []
At this point, short of turning to numpy, we might need to write a custom function. An obvious approach is to return the full number of potential columns, each containing such data as the rows do have. For example:
'''Transposition of row sets with possible gaps'''
from collections import defaultdict
# listTranspose :: [[a]] -> [[a]]
def listTranspose(xss):
'''Transposition of a matrix which may
contain gaps.
'''
def go(xss):
if xss:
h, *t = xss
return (
[[h[0]] + [xs[0] for xs in t if xs]] + (
go([h[1:]] + [xs[1:] for xs in t])
)
) if h and isinstance(h, list) else go(t)
else:
return []
return go(xss)
# TEST ----------------------------------------------------
# main :: IO ()
def main():
'''Tests with various lists of rows or non-row data.'''
def labelledList(kxs):
k, xs = kxs
return k + ': ' + showList(xs)
print(
fTable(
__doc__ + ':\n'
)(labelledList)(fmapFn(showList)(snd))(
fmapTuple(listTranspose)
)([
('Square', [[1, 2, 3], [4, 5, 6], [7, 8, 9]]),
('Rectangle', [[1, 2, 3], [4, 5, 6], [7, 8, 9], [10, 11, 12]]),
('Rows with gaps', [[10, 11], [20], [], [31, 32, 33]]),
('Single row', [[1, 2, 3]]),
('Single row, one cell', [[1]]),
('Not rows', [1, 2, 3]),
('Nothing', [])
])
)
# TEST RESULT FORMATTING ----------------------------------
# fTable :: String -> (a -> String) ->
# (b -> String) -> (a -> b) -> [a] -> String
def fTable(s):
'''Heading -> x display function -> fx display function ->
f -> xs -> tabular string.
'''
def go(xShow, fxShow, f, xs):
ys = [xShow(x) for x in xs]
w = max(map(len, ys))
return s + '\n' + '\n'.join(map(
lambda x, y: y.rjust(w, ' ') + ' -> ' + fxShow(f(x)),
xs, ys
))
return lambda xShow: lambda fxShow: lambda f: lambda xs: go(
xShow, fxShow, f, xs
)
# fmapFn :: (a -> b) -> (r -> a) -> r -> b
def fmapFn(f):
'''The application of f to the result of g.
fmap over a function is composition.
'''
return lambda g: lambda x: f(g(x))
# fmapTuple :: (a -> b) -> (c, a) -> (c, b)
def fmapTuple(f):
'''A pair in which f has been
applied to the second item.
'''
return lambda ab: (ab[0], f(ab[1])) if (
2 == len(ab)
) else None
# show :: a -> String
def show(x):
'''Stringification of a value.'''
def go(v):
return defaultdict(lambda: repr, [
('list', showList)
# ('Either', showLR),
# ('Maybe', showMaybe),
# ('Tree', drawTree)
])[
typeName(v)
](v)
return go(x)
# showList :: [a] -> String
def showList(xs):
'''Stringification of a list.'''
return '[' + ','.join(show(x) for x in xs) + ']'
# snd :: (a, b) -> b
def snd(tpl):
'''Second member of a pair.'''
return tpl[1]
# typeName :: a -> String
def typeName(x):
'''Name string for a built-in or user-defined type.
Selector for type-specific instances
of polymorphic functions.
'''
if isinstance(x, dict):
return x.get('type') if 'type' in x else 'dict'
else:
return 'iter' if hasattr(x, '__next__') else (
type(x).__name__
)
# MAIN ---
if __name__ == '__main__':
main()
- Output:
Transposition of row sets with possible gaps: Square: [[1,2,3],[4,5,6],[7,8,9]] -> [[1,4,7],[2,5,8],[3,6,9]] Rectangle: [[1,2,3],[4,5,6],[7,8,9],[10,11,12]] -> [[1,4,7,10],[2,5,8,11],[3,6,9,12]] Rows with gaps: [[10,11],[20],[],[31,32,33]] -> [[10,20,31],[11,32],[33]] Single row: [[1,2,3]] -> [[1],[2],[3]] Single row, one cell: [[1]] -> [[1]] Not rows: [1,2,3] -> [] Nothing: [] -> []
Quackery
[ ' [ [ ] ]
over 0 peek size of
[] rot
witheach join
witheach
[ dip behead
nested join
nested join ] ] is transpose ( [ --> [ )
' [ [ 1 2 ] [ 3 4 ] [ 5 6 ] ]
dup echo cr cr
transpose dup echo cr cr
transpose echo cr
- Output:
[ [ 1 2 ] [ 3 4 ] [ 5 6 ] ] [ [ 1 3 5 ] [ 2 4 6 ] ] [ [ 1 2 ] [ 3 4 ] [ 5 6 ] ]
R
b <- 1:5
m <- matrix(c(b, b^2, b^3, b^4), 5, 4)
print(m)
tm <- t(m)
print(tm)
Racket
#lang racket
(require math)
(matrix-transpose (matrix [[1 2] [3 4]]))
- Output:
(array #[#[1 3] #[2 4]])
(Another method, without math, and using lists is demonstrated in the Scheme solution.)
Raku
(formerly Perl 6)
# Transposition can be done with the reduced zip meta-operator
# on list-of-lists data structures
say [Z] (<A B C D>, <E F G H>, <I J K L>);
# For native shaped arrays, a more traditional procedure of copying item-by-item
# Here the resulting matrix is also a native shaped array
my @a[3;4] =
[
[<A B C D>],
[<E F G H>],
[<I J K L>],
];
(my $n, my $m) = @a.shape;
my @b[$m;$n];
for ^$m X ^$n -> (\i, \j) {
@b[i;j] = @a[j;i];
}
say @b;
- Output:
((A E I) (B F J) (C G K) (D H L)) [[A E I] [B F J] [C G K] [D H L]]
Rascal
public rel[real, real, real] matrixTranspose(rel[real x, real y, real v] matrix){
return {<y, x, v> | <x, y, v> <- matrix};
}
//a matrix
public rel[real x, real y, real v] matrixA = {
<0.0,0.0,12.0>, <0.0,1.0, 6.0>, <0.0,2.0,-4.0>,
<1.0,0.0,-51.0>, <1.0,1.0,167.0>, <1.0,2.0,24.0>,
<2.0,0.0,4.0>, <2.0,1.0,-68.0>, <2.0,2.0,-41.0>
};
REXX
/*REXX program transposes any sized rectangular matrix, displays before & after matrices*/
@.=; @.1 = 1.02 2.03 3.04 4.05 5.06 6.07 7.08
@.2 = 111 2222 33333 444444 5555555 66666666 777777777
w=0
do row=1 while @.row\==''
do col=1 until @.row==''; parse var @.row A.row.col @.row
w=max(w, length(A.row.col) ) /*max width for elements*/
end /*col*/ /*(used to align ouput).*/
end /*row*/ /* [↑] build matrix A from the @ lists*/
row= row-1 /*adjust for DO loop index increment.*/
do j=1 for row /*process each row of the matrix.*/
do k=1 for col /* " " column " " " */
B.k.j= A.j.k /*transpose the A matrix (into B). */
end /*k*/
end /*j*/
call showMat 'A', row, col /*display the A matrix to terminal.*/
call showMat 'B', col, row /* " " B " " " */
exit /*stick a fork in it, we're all done. */
/*──────────────────────────────────────────────────────────────────────────────────────*/
showMat: arg mat,rows,cols; say; say center( mat 'matrix', (w+1)*cols +4, "─")
do r=1 for rows; _= /*newLine*/
do c=1 for cols; _=_ right( value( mat'.'r"."c), w) /*append.*/
end /*c*/
say _ /*1 line.*/
end /*r*/; return
- output when using the default input:
─────────────────────────────────A matrix───────────────────────────────── 1.02 2.03 3.04 4.05 5.06 6.07 7.08 111 2222 33333 444444 5555555 66666666 777777777 ────────B matrix──────── 1.02 111 2.03 2222 3.04 33333 4.05 444444 5.06 5555555 6.07 66666666 7.08 777777777
Ring
load "stdlib.ring"
transpose = newlist(5,4)
matrix = [[78,19,30,12,36], [49,10,65,42,50], [30,93,24,78,10], [39,68,27,64,29]]
for i = 1 to 5
for j = 1 to 4
transpose[i][j] = matrix[j][i]
see "" + transpose[i][j] + " "
next
see nl
next
Output:
78 49 30 39 19 10 93 68 30 65 24 27 12 42 78 64 36 50 10 29
RLaB
>> m = rand(3,5)
0.41844289 0.476591435 0.75054022 0.226388925 0.963880314
0.91267171 0.941762397 0.464227895 0.693482786 0.203839405
0.261512966 0.157981873 0.26582235 0.11557427 0.0442493069
>> m'
0.41844289 0.91267171 0.261512966
0.476591435 0.941762397 0.157981873
0.75054022 0.464227895 0.26582235
0.226388925 0.693482786 0.11557427
0.963880314 0.203839405 0.0442493069
Ruby
m=[[1, 1, 1, 1],
[2, 4, 8, 16],
[3, 9, 27, 81],
[4, 16, 64, 256],
[5, 25,125, 625]]
puts m.transpose
- Output:
[[1, 2, 3, 4, 5], [1, 4, 9, 16, 25], [1, 8, 27, 64, 125], [1, 16, 81, 256, 625]]
or using 'matrix' from the standard library
require 'matrix'
m=Matrix[[1, 1, 1, 1],
[2, 4, 8, 16],
[3, 9, 27, 81],
[4, 16, 64, 256],
[5, 25,125, 625]]
puts m.transpose
- Output:
Matrix[[1, 2, 3, 4, 5], [1, 4, 9, 16, 25], [1, 8, 27, 64, 125], [1, 16, 81, 256, 625]]
or using zip:
def transpose(m)
m[0].zip(*m[1..-1])
end
p transpose([[1,2,3],[4,5,6]])
- Output:
[[1, 4], [2, 5], [3, 6]]
Run BASIC
mtrx$ ="4, 3, 0, 0.10, 0.20, 0.30, 0.40, 0.50, 0.60, 0.70, 0.80, 0.90, 1.00, 1.10"
print "Transpose of matrix"
call DisplayMatrix mtrx$
print " ="
MatrixT$ =MatrixTranspose$(mtrx$)
call DisplayMatrix MatrixT$
end
function MatrixTranspose$(in$)
w = val(word$(in$, 1, ",")) ' swap w and h parameters
h = val(word$(in$, 2, ","))
t$ = str$(h); ","; str$(w); ","
for i =1 to w
for j =1 to h
t$ = t$ +word$(in$, 2 +i +(j -1) *w, ",") +","
next j
next i
MatrixTranspose$ =left$(t$, len(t$) -1)
end function
sub DisplayMatrix in$ ' Display looking like a matrix!
html "<table border=2>"
w = val(word$(in$, 1, ","))
h = val(word$(in$, 2, ","))
for i =0 to h -1
html "<tr align=right>"
for j =1 to w
term$ = word$(in$, j +2 +i *w, ",")
html "<td>";val(term$);"</td>"
next j
html "</tr>"
next i
html "</table>"
end sub
- Output:
Transpose of matrix
0 | 0.1 | 0.2 | 0.3 |
0.4 | 0.5 | 0.6 | 0.7 |
0.8 | 0.9 | 1.0 | 1.1 |
=
0 | 0.4 | 0.8 |
0.1 | 0.5 | 0.9 |
0.2 | 0.6 | 1.0 |
0.3 | 0.7 | 1.1 |
Rust
version 1
struct Matrix {
dat: [[i32; 3]; 3]
}
impl Matrix {
pub fn transpose_m(a: Matrix) -> Matrix
{
let mut out = Matrix {
dat: [[0, 0, 0],
[0, 0, 0],
[0, 0, 0]
]
};
for i in 0..3{
for j in 0..3{
out.dat[i][j] = a.dat[j][i];
}
}
out
}
pub fn print(self)
{
for i in 0..3 {
for j in 0..3 {
print!("{} ", self.dat[i][j]);
}
print!("\n");
}
}
}
fn main()
{
let a = Matrix {
dat: [[1, 2, 3],
[4, 5, 6],
[7, 8, 9] ]
};
let c = Matrix::transpose_m(a);
c.print();
}
version 2
fn main() {
let m = vec![vec![1, 2, 3], vec![4, 5, 6]];
println!("Matrix:\n{}", matrix_to_string(&m));
let t = matrix_transpose(m);
println!("Transpose:\n{}", matrix_to_string(&t));
}
fn matrix_to_string(m: &Vec<Vec<i32>>) -> String {
m.iter().fold("".to_string(), |a, r| {
a + &r
.iter()
.fold("".to_string(), |b, e| b + "\t" + &e.to_string())
+ "\n"
})
}
fn matrix_transpose(m: Vec<Vec<i32>>) -> Vec<Vec<i32>> {
let mut t = vec![Vec::with_capacity(m.len()); m[0].len()];
for r in m {
for i in 0..r.len() {
t[i].push(r[i]);
}
}
t
}
Output:
Matrix: 1 2 3 4 5 6 Transpose: 1 4 2 5 3 6
Scala
scala> Array.tabulate(4)(i => Array.tabulate(4)(j => i*4 + j))
res12: Array[Array[Int]] = Array(Array(0, 1, 2, 3), Array(4, 5, 6, 7), Array(8, 9, 10, 11), Array(12, 13, 14, 15))
scala> res12.transpose
res13: Array[Array[Int]] = Array(Array(0, 4, 8, 12), Array(1, 5, 9, 13), Array(2, 6, 10, 14), Array(3, 7, 11, 15))
scala> res12 map (_ map ("%2d" format _) mkString " ") mkString "\n"
res16: String =
0 1 2 3
4 5 6 7
8 9 10 11
12 13 14 15
scala> res13 map (_ map ("%2d" format _) mkString " ") mkString "\n"
res17: String =
0 4 8 12
1 5 9 13
2 6 10 14
3 7 11 15
Scheme
(define (transpose m)
(apply map list m))
Seed7
$ include "seed7_05.s7i";
include "float.s7i";
const type: matrix is array array float;
const func matrix: transpose (in matrix: aMatrix) is func
result
var matrix: transposedMatrix is matrix.value;
local
var integer: i is 0;
var integer: j is 0;
begin
transposedMatrix := length(aMatrix[1]) times length(aMatrix) times 0.0;
for i range 1 to length(aMatrix) do
for j range 1 to length(aMatrix[1]) do
transposedMatrix[j][i] := aMatrix[i][j];
end for;
end for;
end func;
const proc: write (in matrix: aMatrix) is func
local
var integer: line is 0;
var integer: column is 0;
begin
for line range 1 to length(aMatrix) do
for column range 1 to length(aMatrix[line]) do
write(" " <& aMatrix[line][column] digits 2);
end for;
writeln;
end for;
end func;
const matrix: testMatrix is [] (
[] (0.0, 0.1, 0.2, 0.3),
[] (0.4, 0.5, 0.6, 0.7),
[] (0.8, 0.9, 1.0, 1.1));
const proc: main is func
begin
writeln("Before Transposition:");
write(testMatrix);
writeln;
writeln("After Transposition:");
write(transpose(testMatrix));
end func;
- Output:
Before Transposition: 0.00 0.10 0.20 0.30 0.40 0.50 0.60 0.70 0.80 0.90 1.00 1.10 After Transposition: 0.00 0.40 0.80 0.10 0.50 0.90 0.20 0.60 1.00 0.30 0.70 1.10
Sidef
func transpose(matrix) {
matrix[0].range.map{|i| matrix.map{_[i]}};
};
var m = [
[1, 1, 1, 1],
[2, 4, 8, 16],
[3, 9, 27, 81],
[4, 16, 64, 256],
[5, 25, 125, 625],
];
transpose(m).each { |row|
"%5d" * row.len -> printlnf(row...);
}
- Output:
1 2 3 4 5 1 4 9 16 25 1 8 27 64 125 1 16 81 256 625
SPAD
(1) -> originalMatrix := matrix [[1, 1, 1, 1],[2, 4, 8, 16], _
[3, 9, 27, 81],[4, 16, 64, 256], _
[5, 25, 125, 625]]
+1 1 1 1 +
| |
|2 4 8 16 |
| |
(1) |3 9 27 81 |
| |
|4 16 64 256|
| |
+5 25 125 625+
Type: Matrix(Integer)
(2) -> transposedMatrix := transpose(originalMatrix)
+1 2 3 4 5 +
| |
|1 4 9 16 25 |
(2) | |
|1 8 27 64 125|
| |
+1 16 81 256 625+
Type: Matrix(Integer)
Domain:Matrix(R)
Sparkling
function transpose(A) {
return map(range(sizeof A), function(k, idx) {
return map(A, function(k, row) {
return row[idx];
});
});
}
Stata
Stata matrices are always real, so there is no ambiguity about the transpose operator. Mata matrices, however, may be real or complex. The transpose operator is actually a conjugate transpose, but there is also a transposeonly() function.
Stata matrices
. mat a=1,2,3\4,5,6
. mat b=a'
. mat list a
a[2,3]
c1 c2 c3
r1 1 2 3
r2 4 5 6
. mat list b
b[3,2]
r1 r2
c1 1 4
c2 2 5
c3 3 6
Mata
: a=1,1i
: a
1 2
+-----------+
1 | 1 1i |
+-----------+
: a'
1
+-------+
1 | 1 |
2 | -1i |
+-------+
: transposeonly(a)
1
+------+
1 | 1 |
2 | 1i |
+------+
Swift
@inlinable
public func matrixTranspose<T>(_ matrix: [[T]]) -> [[T]] {
guard !matrix.isEmpty else {
return []
}
var ret = Array(repeating: [T](), count: matrix[0].count)
for row in matrix {
for j in 0..<row.count {
ret[j].append(row[j])
}
}
return ret
}
@inlinable
public func printMatrix<T>(_ matrix: [[T]]) {
guard !matrix.isEmpty else {
print()
return
}
let rows = matrix.count
let cols = matrix[0].count
for i in 0..<rows {
for j in 0..<cols {
print(matrix[i][j], terminator: " ")
}
print()
}
}
let m1 = [
[1, 2, 3],
[4, 5, 6]
]
print("Input:")
printMatrix(m1)
let m2 = matrixTranspose(m1)
print("Output:")
printMatrix(m2)
- Output:
Input: 1 2 3 4 5 6 Output: 1 4 2 5 3 6
Tailspin
templates transpose
def a: $;
[1..$a(1)::length -> $a(1..last;$)] !
end transpose
templates printMatrix&{w:}
templates formatN
@: [];
$ -> #
'$@ -> $::length~..$w -> ' ';$@(last..1:-1)...;' !
when <1..> do ..|@: $ mod 10; $ ~/ 10 -> #
end formatN
$... -> '|$(1) -> formatN;$(2..last)... -> ', $ -> formatN;';|
' !
end printMatrix
def m: [[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12]];
'before:
' -> !OUT::write
$m -> printMatrix&{w:2} -> !OUT::write
def mT: $m -> transpose;
'
transposed:
' -> !OUT::write
$mT -> printMatrix&{w:2} -> !OUT::write
- Output:
before: | 1, 2, 3, 4| | 5, 6, 7, 8| | 9, 10, 11, 12| transposed: | 1, 5, 9| | 2, 6, 10| | 3, 7, 11| | 4, 8, 12|
Tcl
With core Tcl, representing a matrix as a list of lists:
package require Tcl 8.5
namespace path ::tcl::mathfunc
proc size {m} {
set rows [llength $m]
set cols [llength [lindex $m 0]]
return [list $rows $cols]
}
proc transpose {m} {
lassign [size $m] rows cols
set new [lrepeat $cols [lrepeat $rows ""]]
for {set i 0} {$i < $rows} {incr i} {
for {set j 0} {$j < $cols} {incr j} {
lset new $j $i [lindex $m $i $j]
}
}
return $new
}
proc print_matrix {m {fmt "%.17g"}} {
set max [widest $m $fmt]
lassign [size $m] rows cols
for {set i 0} {$i < $rows} {incr i} {
for {set j 0} {$j < $cols} {incr j} {
set s [format $fmt [lindex $m $i $j]]
puts -nonewline [format "%*s " [lindex $max $j] $s]
}
puts ""
}
}
proc widest {m {fmt "%.17g"}} {
lassign [size $m] rows cols
set max [lrepeat $cols 0]
for {set i 0} {$i < $rows} {incr i} {
for {set j 0} {$j < $cols} {incr j} {
set s [format $fmt [lindex $m $i $j]]
lset max $j [max [lindex $max $j] [string length $s]]
}
}
return $max
}
set m {{1 1 1 1} {2 4 8 16} {3 9 27 81} {4 16 64 256} {5 25 125 625}}
print_matrix $m "%d"
print_matrix [transpose $m] "%d"
- Output:
1 1 1 1 2 4 8 16 3 9 27 81 4 16 64 256 5 25 125 625 1 2 3 4 5 1 4 9 16 25 1 8 27 64 125 1 16 81 256 625
package require struct::matrix
struct::matrix M
M deserialize {5 4 {{1 1 1 1} {2 4 8 16} {3 9 27 81} {4 16 64 256} {5 25 125 625}}}
M format 2string
M transpose
M format 2string
- Output:
1 1 1 1 2 4 8 16 3 9 27 81 4 16 64 256 5 25 125 625 1 2 3 4 5 1 4 9 16 25 1 8 27 64 125 1 16 81 256 625
TI-83 BASIC , TI-89 BASIC
TI-83: Assuming the original matrix is in [A], place its transpose in [B]:
[A]T->[B]
The T operator can be found in the matrix math menu.
TI-89: The same except that matrix variables do not have special names:
AT → B
True BASIC
OPTION BASE 0
DIM matriz(3, 4)
DATA 78, 19, 30, 12, 36
DATA 49, 10, 65, 42, 50
DATA 30, 93, 24, 78, 10
DATA 39, 68, 27, 64, 29
FOR f = 0 TO 3
FOR c = 0 TO 4
READ matriz(f, c)
NEXT c
NEXT f
DIM mtranspuesta(0 TO 4, 0 TO 3)
FOR fila = LBOUND(matriz,1) TO UBOUND(matriz,1)
FOR columna = LBOUND(matriz,2) TO UBOUND(matriz,2)
LET mtranspuesta(columna, fila) = matriz(fila, columna)
PRINT matriz(fila, columna);
NEXT columna
PRINT
NEXT fila
PRINT
FOR fila = LBOUND(mtranspuesta,1) TO UBOUND(mtranspuesta,1)
FOR columna = LBOUND(mtranspuesta,2) TO UBOUND(mtranspuesta,2)
PRINT mtranspuesta(fila, columna);
NEXT columna
PRINT
NEXT fila
END
Ursala
Matrices are stored as lists of lists, and transposing them is a built in operation.
#cast %eLL
example =
~&K7 <
<1.,2.,3.,4.>,
<5.,6.,7.,8.>,
<9.,10.,11.,12.>>
For a more verbose version, replace the ~&K7 operator with the standard library function named transpose.
- Output:
< <1.000000e+00,5.000000e+00,9.000000e+00>, <2.000000e+00,6.000000e+00,1.000000e+01>, <3.000000e+00,7.000000e+00,1.100000e+01>, <4.000000e+00,8.000000e+00,1.200000e+01>>
VBA
Function transpose(m As Variant) As Variant
transpose = WorksheetFunction.transpose(m)
End Function
VBScript
'create and display the initial matrix
WScript.StdOut.WriteLine "Initial Matrix:"
x = 4 : y = 6 : n = 1
Dim matrix()
ReDim matrix(x,y)
For i = 0 To y
For j = 0 To x
matrix(j,i) = n
If j < x Then
WScript.StdOut.Write n & vbTab
Else
WScript.StdOut.Write n
End If
n = n + 1
Next
WScript.StdOut.WriteLine
Next
'display the trasposed matrix
WScript.StdOut.WriteBlankLines(1)
WScript.StdOut.WriteLine "Transposed Matrix:"
For i = 0 To x
For j = 0 To y
If j < y Then
WScript.StdOut.Write matrix(i,j) & vbTab
Else
WScript.StdOut.Write matrix(i,j)
End If
Next
WScript.StdOut.WriteLine
Next
- Output:
Initial Matrix: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 Transposed Matrix: 1 6 11 16 21 26 31 2 7 12 17 22 27 32 3 8 13 18 23 28 33 4 9 14 19 24 29 34 5 10 15 20 25 30 35
Visual Basic
Option Explicit
'----------------------------------------------------------------------
Function TransposeMatrix(InitMatrix() As Long, TransposedMatrix() As Long)
Dim l1 As Long, l2 As Long, u1 As Long, u2 As Long, r As Long, c As Long
l1 = LBound(InitMatrix, 1)
l2 = LBound(InitMatrix, 2)
u1 = UBound(InitMatrix, 1)
u2 = UBound(InitMatrix, 2)
ReDim TransposedMatrix(l2 To u2, l1 To u1)
For r = l1 To u1
For c = l2 To u2
TransposedMatrix(c, r) = InitMatrix(r, c)
Next c
Next r
End Function
'----------------------------------------------------------------------
Sub PrintMatrix(a() As Long)
Dim l1 As Long, l2 As Long, u1 As Long, u2 As Long, r As Long, c As Long
Dim s As String * 8
l1 = LBound(a(), 1)
l2 = LBound(a(), 2)
u1 = UBound(a(), 1)
u2 = UBound(a(), 2)
For r = l1 To u1
For c = l2 To u2
RSet s = Str$(a(r, c))
Debug.Print s;
Next c
Debug.Print
Next r
End Sub
'----------------------------------------------------------------------
Sub TranspositionDemo(ByVal DimSize1 As Long, ByVal DimSize2 As Long)
Dim r, c, cc As Long
Dim a() As Long
Dim b() As Long
cc = DimSize2
DimSize1 = DimSize1 - 1
DimSize2 = DimSize2 - 1
ReDim a(0 To DimSize1, 0 To DimSize2)
For r = 0 To DimSize1
For c = 0 To DimSize2
a(r, c) = (cc * r) + c + 1
Next c
Next r
Debug.Print "initial matrix:"
PrintMatrix a()
TransposeMatrix a(), b()
Debug.Print "transposed matrix:"
PrintMatrix b()
End Sub
'----------------------------------------------------------------------
Sub Main()
TranspositionDemo 3, 3
TranspositionDemo 3, 7
End Sub
- Output:
initial matrix: 1 2 3 4 5 6 7 8 9 transposed matrix: 1 4 7 2 5 8 3 6 9 initial matrix: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 transposed matrix: 1 8 15 2 9 16 3 10 17 4 11 18 5 12 19 6 13 20 7 14 21
Wortel
The @zipm
operator zips together an array of arrays, this is the same as transposition if the matrix is represented as an array of arrays.
@zipm [[1 2 3] [4 5 6] [7 8 9]]
Returns:
[[1 4 7] [2 5 8] [3 6 9]]
Wren
import "/matrix" for Matrix
import "/fmt" for Fmt
var m = Matrix.new([
[ 1, 2, 3],
[ 4, 5, 6],
[ 7, 8, 9],
[10, 11, 12]
])
System.print("Original:\n")
Fmt.mprint(m, 2, 0)
System.print("\nTransposed:\n")
Fmt.mprint(m.transpose, 2, 0)
- Output:
Original: | 1 2 3| | 4 5 6| | 7 8 9| |10 11 12| Transposed: | 1 4 7 10| | 2 5 8 11| | 3 6 9 12|
XPL0
Separate memory for the transposed matrix must be used because of XPL0's unusual array configuration. It can't simply reorder the elements stored in the original array's memory.
proc Transpose(M, R, C, N); \Transpose matrix M to N
int M, R, C, N; \rows and columns
int I, J;
[for I:= 0 to R-1 do
for J:= 0 to C-1 do
N(J,I):= M(I,J);
];
proc ShowMat(M, R, C); \Display matrix M
int M, R, C; \rows and columns
int I, J;
[for I:= 0 to R-1 do
[for J:= 0 to C-1 do
RlOut(0, float(M(I,J)));
CrLf(0);
];
];
int M, N(4,3);
[M:= [[1, 2, 3, 4], \3 rows by 4 columns
[5, 6, 7, 8],
[9,10,11,12]];
Format(4, 0);
ShowMat(M, 3, 4);
CrLf(0);
Transpose(M, 3, 4, N);
ShowMat(N, 4, 3);
]
- Output:
1 2 3 4 5 6 7 8 9 10 11 12 1 5 9 2 6 10 3 7 11 4 8 12
Yabasic
dim matriz(4,5)
dim mtranspuesta(5,4)
for fila = 1 to arraysize(matriz(), 1)
for columna = 1 to arraysize(matriz(), 2)
read matriz(fila, columna)
print matriz(fila, columna);
mtranspuesta(columna, fila) = matriz(fila, columna)
next columna
print
next fila
print
for fila = 1 to arraysize(mtranspuesta(), 1)
for columna = 1 to arraysize(mtranspuesta(), 2)
print mtranspuesta(fila, columna);
next columna
print
next fila
end
data 78,19,30,12,36
data 49,10,65,42,50
data 30,93,24,78,10
data 39,68,27,64,29
zkl
Using the GNU Scientific Library:
var [const] GSL=Import("zklGSL"); // libGSL (GNU Scientific Library)
GSL.Matrix(2,3).set(1,2,3, 4,5,6).transpose().format(5).println(); // in place
println("---");
GSL.Matrix(2,2).set(1,2, 3,4).transpose().format(5).println(); // in place
println("---");
GSL.Matrix(3,1).set(1,2,3).transpose().format(5).println(); // in place
- Output:
1.00, 4.00 2.00, 5.00 3.00, 6.00 --- 1.00, 3.00 2.00, 4.00 --- 1.00, 2.00, 3.00
Or, using lists:
fcn transpose(M){
if(M.len()==1) M[0].pump(List,List.create); // 1 row --> n columns
else M[0].zip(M.xplode(1));
}
The list xplode method pushes list contents on to the call stack.
m:=T(T(1,2,3),T(4,5,6)); transpose(m).println();
m:=L(L(1,"a"),L(2,"b"),L(3,"c")); transpose(m).println();
transpose(L(L(1,2,3))).println();
transpose(L(L(1),L(2),L(3))).println();
transpose(L(L(1))).println();
- Output:
L(L(1,4),L(2,5),L(3,6)) L(L(1,2,3),L("a","b","c")) L(L(1),L(2),L(3)) (L(1,2,3)) L(L(1))
zonnon
module MatrixOps;
type
Matrix = array {math} *,* of integer;
procedure WriteMatrix(x: array {math} *,* of integer);
var
i,j: integer;
begin
for i := 0 to len(x,0) - 1 do
for j := 0 to len(x,1) - 1 do
write(x[i,j]);
end;
writeln;
end
end WriteMatrix;
procedure Transposition;
var
m,x: Matrix;
begin
m := [[1,2,3],[3,4,5]]; (* matrix initialization *)
x := !m; (* matrix trasposition *)
WriteMatrix(x);
end Transposition;
begin
Transposition;
end MatrixOps.
- Programming Tasks
- Matrices
- 11l
- 360 Assembly
- 68000 Assembly
- ACL2
- Action!
- ActionScript
- Ada
- Agda
- ALGOL 68
- Amazing Hopper
- APL
- AppleScript
- Arturo
- AutoHotkey
- AWK
- BASIC
- BASIC256
- BBC BASIC
- Burlesque
- C
- C sharp
- C++
- Boost.uBLAS
- Clojure
- CoffeeScript
- Common Lisp
- D
- Delphi
- EchoLisp
- EDSAC order code
- Elixir
- ELLA
- Emacs Lisp
- Cl-lib
- Erlang
- Euphoria
- Excel
- F Sharp
- Factor
- Fermat
- Forth
- Forth Scientific Library
- Fortran
- FreeBASIC
- Frink
- Fōrmulæ
- GAP
- Go
- Groovy
- Haskell
- Haxe
- HicEst
- Hope
- Icon
- Unicon
- IDL
- Idris
- J
- Java
- JavaScript
- Joy
- Jq
- Jsish
- Julia
- K
- Klong
- Kotlin
- Lang5
- LFE
- Liberty BASIC
- Lua
- Maple
- Mathematica
- Wolfram Language
- MATLAB
- Maxima
- MAXScript
- Nial
- Nim
- Objeck
- OCaml
- Octave
- OxygenBasic
- PARI/GP
- Pascal
- Perl
- Phix
- PHP
- Picat
- PicoLisp
- PL/I
- Pop11
- PostScript
- Initlib
- PowerBASIC
- PowerShell
- Prolog
- PureBasic
- Python
- Quackery
- R
- Racket
- Raku
- Rascal
- REXX
- Ring
- RLaB
- Ruby
- Run BASIC
- Rust
- Scala
- Scheme
- Seed7
- Sidef
- SPAD
- Sparkling
- Stata
- Swift
- Tailspin
- Tcl
- Tcllib
- TI-83 BASIC
- TI-89 BASIC
- True BASIC
- Ursala
- VBA
- VBScript
- Visual Basic
- Wortel
- Wren
- Wren-matrix
- Wren-fmt
- XPL0
- Yabasic
- Zkl
- Zonnon
- Pages with too many expensive parser function calls