Matrix transposition: Difference between revisions

Content added Content deleted
mNo edit summary
m (syntax highlighting fixup automation)
Line 3: Line 3:
<br><br>
<br><br>
=={{header|11l}}==
=={{header|11l}}==
<lang 11l>F transpose(&matrix)
<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))</lang>
print(transpose(&m))</syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>
Line 23: Line 23:
</pre>
</pre>
=={{header|360 Assembly}}==
=={{header|360 Assembly}}==
<lang 360asm>...
<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
...</lang>
...</syntaxhighlight>


=={{header|68000 Assembly}}==
=={{header|68000 Assembly}}==


<lang 68000devpac>Transpose2DArray_B:
<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</lang>
RTS</syntaxhighlight>


=={{header|ACL2}}==
=={{header|ACL2}}==
<lang Lisp>(defun cons-each (xs xss)
<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)))))</lang>
(transpose-list (rest xss)))))</syntaxhighlight>


=={{header|Action!}}==
=={{header|Action!}}==
<lang Action!>DEFINE PTR="CARD"
<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</lang>
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.
<lang ActionScript>function transpose( m:Array):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]);</lang>
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:
<lang ada>with Ada.Numerics.Real_Arrays; use Ada.Numerics.Real_Arrays;
<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;</lang>
end Matrix_Transpose;</syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>
Line 273: Line 273:


=={{header|Agda}}==
=={{header|Agda}}==
<lang agda>module Matrix where
<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</lang>
b = transpose a</syntaxhighlight>


'''b''' evaluates to the following normal form:
'''b''' evaluates to the following normal form:


<lang agda>(1 ∷ 4 ∷ []) ∷ (2 ∷ 5 ∷ []) ∷ (3 ∷ 6 ∷ []) ∷ []</lang>
<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}}
<lang algol68>main:(
<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))
)</lang>
)</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,
<lang apl>
<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,


<lang applescript>on run
<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</lang>
end transpose</syntaxhighlight>




Line 442: Line 442:
{{trans|JavaScript}}
{{trans|JavaScript}}


<lang applescript>-- TRANSPOSE -----------------------------------------------------------------
<syntaxhighlight lang="applescript">-- TRANSPOSE -----------------------------------------------------------------


-- transpose :: [[a]] -> [[a]]
-- transpose :: [[a]] -> [[a]]
Line 493: Line 493:
end script
end script
end if
end if
end mReturn</lang>
end mReturn</syntaxhighlight>


{{Out}}
{{Out}}
<lang AppleScript>{{1, 4, 7, 10}, {2, 5, 8, 11}, {3, 6, 9, 12}}</lang>
<syntaxhighlight lang="applescript">{{1, 4, 7, 10}, {2, 5, 8, 11}, {3, 6, 9, 12}}</syntaxhighlight>


=={{header|Arturo}}==
=={{header|Arturo}}==


<lang rebol>transpose: function [a][
<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</lang>
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===
<lang AutoHotkey>Transpose(M){
<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
}</lang>
}</syntaxhighlight>
Examples:<lang AutoHotkey>Matrix := [[1,2,3],[4,5,6],[7,8,9],[10,11,12]]
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")
}</lang>
}</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===
<lang AWK># Usage: GAWK -f MATRIX_TRANSPOSITION.AWK filename
<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
}</lang>
}</syntaxhighlight>
<p><b>Input:</b></p>
<p><b>Input:</b></p>
<pre>
<pre>
Line 731: Line 731:


=={{header|BASIC256}}==
=={{header|BASIC256}}==
<lang BASIC256>arraybase 1
<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</lang>
end</syntaxhighlight>




=={{header|BBC BASIC}}==
=={{header|BBC BASIC}}==
{{works with|BBC BASIC for Windows}}
{{works with|BBC BASIC for Windows}}
<lang bbcbasic> INSTALL @lib$+"ARRAYLIB"
<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%</lang>
NEXT row%</syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>
Line 793: Line 793:
=={{header|Burlesque}}==
=={{header|Burlesque}}==


<lang 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.
<lang c>#include <stdio.h>
<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;
}</lang>
}</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.
<lang c>#include <stdio.h>
<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;
}</lang>
}</syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>
Line 896: Line 896:


=={{header|C sharp|C#}}==
=={{header|C sharp|C#}}==
<lang csharp>using System;
<syntaxhighlight lang="csharp">using System;
using System.Text;
using System.Text;


Line 927: Line 927:
}
}
}
}
}</lang>
}</syntaxhighlight>


=={{header|C++}}==
=={{header|C++}}==
Line 933: Line 933:


{{libheader|Boost.uBLAS}}
{{libheader|Boost.uBLAS}}
<lang cpp>#include <boost/numeric/ublas/matrix.hpp>
<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;
}</lang>
}</syntaxhighlight>


{{out}}
{{out}}
Line 956: Line 956:
===Generic solution===
===Generic solution===
;main.cpp
;main.cpp
<lang cpp>#include <iostream>
<syntaxhighlight lang="cpp">#include <iostream>
#include "matrix.h"
#include "matrix.h"


Line 994: Line 994:
}
}


} /* main() */</lang>
} /* main() */</syntaxhighlight>
;matrix.h
;matrix.h
<lang cpp>#ifndef _MATRIX_H
<syntaxhighlight lang="cpp">#ifndef _MATRIX_H
#define _MATRIX_H
#define _MATRIX_H


Line 1,190: Line 1,190:
}
}


#endif /* _MATRIX_H */</lang>
#endif /* _MATRIX_H */</syntaxhighlight>


{{out}}
{{out}}
Line 1,205: Line 1,205:


===Easy Mode===
===Easy Mode===
<lang cpp>#include <iostream>
<syntaxhighlight lang="cpp">#include <iostream>


int main(){
int main(){
Line 1,240: Line 1,240:
return 0;
return 0;
}</lang>
}</syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>
Line 1,257: Line 1,257:


=={{header|Clojure}}==
=={{header|Clojure}}==
<lang lisp>(defmulti matrix-transpose
<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}}==
<lang coffeescript>transpose = (matrix) ->
<syntaxhighlight lang="coffeescript">transpose = (matrix) ->
(t[i] for t in matrix) for i in [0...matrix[0].length]</lang>
(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:
<lang lisp>(defun transpose (m)
<syntaxhighlight lang="lisp">(defun transpose (m)
(apply #'mapcar #'list m))</lang>
(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:
<lang lisp>;; Transpose a mxn matrix A to a nxm matrix B=A'.
<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))</lang>
B))</syntaxhighlight>


=={{header|D}}==
=={{header|D}}==
===Standard Version===
===Standard Version===
<lang d>void main() {
<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);
}</lang>
}</syntaxhighlight>
{{out}}
{{out}}
<pre>10 14 18
<pre>10 14 18
Line 1,317: Line 1,317:


===Locally Procedural Style===
===Locally Procedural Style===
<lang d>T[][] transpose(T)(in T[][] m) pure nothrow {
<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);
}</lang>
}</syntaxhighlight>
Same output.
Same output.


===Functional Style===
===Functional Style===
<lang d>import std.stdio, std.algorithm, std.range, std.functional;
<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);
}</lang>
}</syntaxhighlight>
Same output.
Same output.
=={{header|Delphi}}==
=={{header|Delphi}}==
See [[#Pascal]];
See [[#Pascal]];
=={{header|EchoLisp}}==
=={{header|EchoLisp}}==
<lang scheme>
<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===
<lang edsac>
<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.
<lang edsac>
<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}}==
<lang elixir>m = [[1, 1, 1, 1],
<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)</lang>
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:<lang ella>MAC TRANSPOSE = ([INT n][INT m]TYPE t: matrix) -> [m][n]t:
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].</lang>
[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}}


<lang lisp>(require '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)))</lang>
(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.


<lang erlang>
<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}}==
<lang euphoria>function transpose(sequence in)
<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)</lang>
? 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...
<lang fsharp>let transpose (mtx : _ [,]) = Array2D.init (mtx.GetLength 1) (mtx.GetLength 0) (fun x y -> mtx.[y,x])</lang>
<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.
<lang factor>( scratchpad ) { { 1 2 3 } { 4 5 6 } } flip .
<syntaxhighlight lang="factor">( scratchpad ) { { 1 2 3 } { 4 5 6 } } flip .
{ { 1 4 } { 2 5 } { 3 6 } }</lang>
{ { 1 4 } { 2 5 } { 3 6 } }</syntaxhighlight>


=={{header|Fermat}}==
=={{header|Fermat}}==
Matrix transpose is built in.
Matrix transpose is built in.
<lang fermat>
<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}}
<lang forth>S" fsl-util.fs" REQUIRED
<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</lang>
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:
<lang fortran>integer, parameter :: n = 3, m = 5
<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</lang>
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:
<lang fortran>REAL A(3,5), B(5,3)
<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</lang>
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:
<lang fortran> REAL A(3,5), B(5,3)
<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</lang>
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 <lang Fortran> DIMENSION A(3,5),B(5,3),C(5,3)
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</lang>
END</syntaxhighlight>


Output:
Output:
Line 1,922: Line 1,922:


=={{header|FreeBASIC}}==
=={{header|FreeBASIC}}==
<lang freebasic>Dim matriz(0 To 3, 0 To 4) As Integer = {{78,19,30,12,36},_
<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</lang>
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.
<lang frink>
<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}}==
<lang gap>originalMatrix := [[1, 1, 1, 1],
<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);</lang>
transposedMatrix := TransposedMat(originalMatrix);</syntaxhighlight>


=={{header|Go}}==
=={{header|Go}}==
===Library gonum/mat===
===Library gonum/mat===
<lang go>package main
<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()))
}</lang>
}</syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>
Line 2,015: Line 2,015:


===Library go.matrix===
===Library go.matrix===
<lang go>package main
<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)
}</lang>
}</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:
<lang go>package main
<syntaxhighlight lang="go">package main


import "fmt"
import "fmt"
Line 2,081: Line 2,081:
}
}
return r
return r
}</lang>
}</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.
<lang go>package main
<syntaxhighlight lang="go">package main


import "fmt"
import "fmt"
Line 2,142: Line 2,142:
}
}
return r
return r
}</lang>
}</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.
<lang go>package main
<syntaxhighlight lang="go">package main


import "fmt"
import "fmt"
Line 2,217: Line 2,217:
}
}
m.stride = h
m.stride = h
}</lang>
}</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:
<lang groovy>def matrix = [ [ 1, 2, 3, 4 ],
<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 }</lang>
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'':
<lang haskell>*Main> transpose [[1,2],[3,4],[5,6]]
<syntaxhighlight lang="haskell">*Main> transpose [[1,2],[3,4],[5,6]]
[[1,3,5],[2,4,6]]</lang>
[[1,3,5],[2,4,6]]</syntaxhighlight>


For matrices in arrays, one can use ''ixmap'':
For matrices in arrays, one can use ''ixmap'':
<lang haskell>import Data.Array
<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</lang>
(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:
<lang haskell>
<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===
<lang haskell>import 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</lang>
print $ tr a</syntaxhighlight>
{{out}}
{{out}}
<pre>(3><2)
<pre>(3><2)
Line 2,287: Line 2,287:


=={{header|Haxe}}==
=={{header|Haxe}}==
<lang haxe>class Matrix {
<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);
}
}
}</lang>
}</syntaxhighlight>
{{Out}}
{{Out}}
<pre>[1,1,1,1]
<pre>[1,1,1,1]
Line 2,316: Line 2,316:


=={{header|HicEst}}==
=={{header|HicEst}}==
<lang hicest>REAL :: mtx(2, 4)
<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</lang>
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}}==
<lang hope>uses lists;
<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);</lang>
--- transpose n <= map head n :: transpose (map tail n);</syntaxhighlight>


=={{header|Icon}} and {{header|Unicon}}==
=={{header|Icon}} and {{header|Unicon}}==
<lang Icon>procedure transpose_matrix (matrix)
<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</lang>
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>
<lang idl>m=[[1,1,1,1],[2, 4, 8, 16],[3, 9,27, 81],[5, 25,125, 625]]
<syntaxhighlight lang="idl">m=[[1,1,1,1],[2, 4, 8, 16],[3, 9,27, 81],[5, 25,125, 625]]
print,transpose(m)</lang>
print,transpose(m)</syntaxhighlight>


=={{header|Idris}}==
=={{header|Idris}}==
<lang idris>Idris> transpose [[1,2],[3,4],[5,6]]
<syntaxhighlight lang="idris">Idris> transpose [[1,2],[3,4],[5,6]]
[[1, 3, 5], [2, 4, 6]] : List (List Integer)</lang>
[[1, 3, 5], [2, 4, 6]] : List (List Integer)</syntaxhighlight>


=={{header|J}}==
=={{header|J}}==
Line 2,392: Line 2,392:


'''Example:'''
'''Example:'''
<lang j> ]matrix=: (^/ }:) >:i.5 NB. make and show example matrix
<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</lang>
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}}==
<lang java>import java.util.Arrays;
<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:
}
}
}
}
}</lang>
}</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
<lang javascript>function Matrix(ary) {
<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());</lang>
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):
<lang javascript>
<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===


<lang JavaScript>(() => {
<syntaxhighlight lang="javascript">(() => {
"use strict";
"use strict";


Line 2,526: Line 2,526:
// MAIN ---
// MAIN ---
return main();
return main();
})();</lang>
})();</syntaxhighlight>
{{Out}}
{{Out}}
<lang JavaScript>[[1,4,7],[2,5,8],[3,6,9]]</lang>
<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=Joy>DEFINE transpose == [[null] [true] [[null] some] ifte]
<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.
<lang jq>def transpose:
<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 ;</lang>
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.


<lang javascript>/* Matrix transposition, multiplication, identity, and exponentiation, in Jsish */
<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');</lang>
provide('Matrix', '0.60');</syntaxhighlight>


Then a unitTest of the transposition.
Then a unitTest of the transposition.


<lang javascript>/* Matrix transposition, in Jsish */
<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!=
*/</lang>
*/</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.
<lang Julia>julia> [1 2 3 ; 4 5 6] # a 2x3 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</lang>
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>
<lang k> {x^\:-1_ x}1+!:5
<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)</lang>
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>
<lang k> [5 5]:^!25
<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]]</lang>
[4 9 14 19 24]]</syntaxhighlight>


=={{header|Kotlin}}==
=={{header|Kotlin}}==
<lang scala>// version 1.1.3
<syntaxhighlight lang="scala">// version 1.1.3


typealias Vector = DoubleArray
typealias Vector = DoubleArray
Line 2,714: Line 2,714:
}
}
}
}
}</lang>
}</syntaxhighlight>


=={{header|Lang5}}==
=={{header|Lang5}}==
<lang Lang5>12 iota [3 4] reshape 1 + dup .
<syntaxhighlight lang="lang5">12 iota [3 4] reshape 1 + dup .
1 transpose .</lang>
1 transpose .</syntaxhighlight>
{{out}}
{{out}}
<pre>[
<pre>[
Line 2,733: Line 2,733:
=={{header|LFE}}==
=={{header|LFE}}==


<lang lisp>
<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:


<lang lisp>
<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.
<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"
<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$</lang>
call DisplayMatrix MatrixT$</syntaxhighlight>


{{out}}
{{out}}
Line 2,785: Line 2,785:


=={{header|Lua}}==
=={{header|Lua}}==
<lang lua>function Transpose( m )
<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</lang>
end</syntaxhighlight>


Using apply map list
Using apply map list
<lang lua>function map(f, a)
<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"))</lang>
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}}==
<lang mathematica>originalMatrix = {{1, 1, 1, 1},
<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]</lang>
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]].
<lang Matlab>>> transpose([1 2;3 4])
<syntaxhighlight lang="matlab">>> transpose([1 2;3 4])


ans =
ans =
Line 2,893: Line 2,893:


1 3
1 3
2 4</lang>
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
<lang Matlab>xy = {{1,2,3,4},{1,2,3,4},{1,2,3,4}}
<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)</lang>
yx = feval(@(x) cellfun(@(varargin)[varargin],x{:},'un',0), xy)</syntaxhighlight>


=={{header|Maxima}}==
=={{header|Maxima}}==
<lang maxima>originalMatrix : matrix([1, 1, 1, 1],
<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);</lang>
transposedMatrix : transpose(originalMatrix);</syntaxhighlight>


=={{header|MAXScript}}==
=={{header|MAXScript}}==
Uses the built in transpose() function
Uses the built in transpose() function
<lang maxscript>m = bigMatrix 5 4
<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</lang>
m = transpose m</syntaxhighlight>


=={{header|Nial}}==
=={{header|Nial}}==
make an array
make an array
<lang nial>|a := 2 3 reshape count 6
<syntaxhighlight lang="nial">|a := 2 3 reshape count 6
=1 2 3
=1 2 3
=4 5 6</lang>
=4 5 6</syntaxhighlight>
transpose it
transpose it
<lang nial>|transpose a
<syntaxhighlight lang="nial">|transpose a
=1 4
=1 4
=2 5
=2 5
=3 6</lang>
=3 6</syntaxhighlight>


=={{header|Nim}}==
=={{header|Nim}}==
For statically sized arrays:
For statically sized arrays:
<lang nim>proc transpose[X, Y; T](s: array[Y, array[X, T]]): array[X, array[Y, T]] =
<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 ""</lang>
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:
<lang nim>proc transpose[T](s: seq[seq[T]]): seq[seq[T]] =
<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)</lang>
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}}==
<lang 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:


<lang ocaml>open 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) ;;</lang>
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:
<lang ocaml>let rec transpose m =
<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)</lang>
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}}==
<lang octave>a = [ 1, 1, 1, 1 ;
<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</lang>
ctransp = a'; % conjugate transpose</syntaxhighlight>


=={{header|OxygenBasic}}==
=={{header|OxygenBasic}}==
<lang 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 parigp>M~</lang>
<syntaxhighlight lang="parigp">M~</syntaxhighlight>


In PARI the function is
In PARI the function is
<lang C>gtrans(M)</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}}==
<lang pascal>Program Transpose;
<syntaxhighlight lang="pascal">Program Transpose;


const
const
Line 3,165: Line 3,165:
writeln;
writeln;
end;
end;
end.</lang>
end.</syntaxhighlight>
{{out}}
{{out}}
<pre>% ./Transpose
<pre>% ./Transpose
Line 3,182: Line 3,182:
=={{header|Perl}}==
=={{header|Perl}}==
{{libheader|Math::Matrix}}
{{libheader|Math::Matrix}}
<lang perl>use 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;</lang>
$m->transpose->print;</syntaxhighlight>


{{out}}
{{out}}
Line 3,202: Line 3,202:
</pre>
</pre>
Manually:
Manually:
<lang perl>my @m = (
<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]);
}</lang>
}</syntaxhighlight>


=={{header|Phix}}==
=={{header|Phix}}==
<!--<lang Phix>(phixonline)-->
<!--<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>
<!--</lang>-->
<!--</syntaxhighlight>-->


=={{header|PHP}}==
=={{header|PHP}}==
====Up to PHP version 5.6====
====Up to PHP version 5.6====
<lang php>
<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);
}</lang>
}</syntaxhighlight>




====Starting with PHP 5.6====
====Starting with PHP 5.6====
<lang php>
<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).
<lang Picat>import util.
<syntaxhighlight lang="picat">import util.


go =>
go =>
Line 3,299: Line 3,299:
end,
end,
M := M ++ [NewRow]
M := M ++ [NewRow]
end.</lang>
end.</syntaxhighlight>


{{out}}
{{out}}
Line 3,343: Line 3,343:


=={{header|PicoLisp}}==
=={{header|PicoLisp}}==
<lang PicoLisp>(de matTrans (Mat)
<syntaxhighlight lang="picolisp">(de matTrans (Mat)
(apply mapcar Mat list) )
(apply mapcar Mat list) )


(matTrans '((1 2 3) (4 5 6)))</lang>
(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}}==
<lang PL/I>/* The short method: */
<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. */</lang>
/* Any reference to B gives the transpose of matrix A. */</syntaxhighlight>
Traditional method:
Traditional method:
<lang PL/I>/* Transpose matrix A, result at B. */
<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;</lang>
end transpose;</syntaxhighlight>


=={{header|Pop11}}==
=={{header|Pop11}}==
<lang pop11>define transpose(m) -> res;
<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;</lang>
enddefine;</syntaxhighlight>


=={{header|PostScript}}==
=={{header|PostScript}}==
{{libheader|initlib}}
{{libheader|initlib}}
<lang postscript>/transpose {
<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
}.</lang>
}.</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.
<lang powerbasic>#COMPILE EXE
<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</lang>
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}}
<lang Prolog>% transposition of a rectangular matrix
<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).</lang>
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.
<lang PureBasic>Procedure transposeMatrix(Array a(2), Array trans(2))
<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</lang>
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}}==
<lang python>m=((1, 1, 1, 1),
<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)))</lang>
# 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:
<lang python># transpose :: Matrix a -> Matrix a
<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)
)</lang>
)</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:


<lang python># Uneven list of lists
<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:
)
)


# --> []</lang>
# --> []</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}}
<lang python>'''Transposition of row sets with possible gaps'''
<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()</lang>
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}}==


<lang 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</lang>
transpose echo cr</syntaxhighlight>


{{out}}
{{out}}
Line 3,977: Line 3,977:


=={{header|R}}==
=={{header|R}}==
<lang R>b <- 1:5
<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)</lang>
print(tm)</syntaxhighlight>


=={{header|Racket}}==
=={{header|Racket}}==
<lang 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 perl6># Transposition can be done with the reduced zip meta-operator
<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;</lang>
say @b;</syntaxhighlight>


{{output}}
{{output}}
Line 4,028: Line 4,028:


=={{header|Rascal}}==
=={{header|Rascal}}==
<lang Rascal>public rel[real, real, real] matrixTranspose(rel[real x, real y, real v] matrix){
<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>
};</lang>
};</syntaxhighlight>


=={{header|REXX}}==
=={{header|REXX}}==
<lang rexx>/*REXX program transposes any sized rectangular matrix, displays before & after matrices*/
<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</lang>
end /*r*/; return</syntaxhighlight>
{{out|output|text=&nbsp; when using the default input:}}
{{out|output|text=&nbsp; when using the default input:}}
<pre>
<pre>
Line 4,082: Line 4,082:


=={{header|Ring}}==
=={{header|Ring}}==
<lang 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}}==
<lang RLaB> >> m = rand(3,5)
<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</lang>
0.963880314 0.203839405 0.0442493069</syntaxhighlight>


=={{header|Ruby}}==
=={{header|Ruby}}==
<lang ruby>m=[[1, 1, 1, 1],
<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</lang>
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
<lang ruby>require 'matrix'
<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</lang>
puts m.transpose</syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>
Line 4,140: Line 4,140:
</pre>
</pre>
or using zip:
or using zip:
<lang ruby>def transpose(m)
<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]])</lang>
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}}==
<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"
<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</lang>
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===
<lang rust>
<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===
<lang rust>
<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}}==
<lang scala>scala> Array.tabulate(4)(i => Array.tabulate(4)(j => i*4 + j))
<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</lang>
3 7 11 15</syntaxhighlight>


=={{header|Scheme}}==
=={{header|Scheme}}==
<lang scheme>(define (transpose m)
<syntaxhighlight lang="scheme">(define (transpose m)
(apply map list m))</lang>
(apply map list m))</syntaxhighlight>


=={{header|Seed7}}==
=={{header|Seed7}}==
<lang seed7>$ include "seed7_05.s7i";
<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;</lang>
end func;</syntaxhighlight>


{{out}}
{{out}}
Line 4,372: Line 4,372:


=={{header|Sidef}}==
=={{header|Sidef}}==
<lang ruby>func transpose(matrix) {
<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...);
}</lang>
}</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}}
<lang SPAD>(1) -> originalMatrix := matrix [[1, 1, 1, 1],[2, 4, 8, 16], _
<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)</lang>
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}}==
<lang sparkling>function transpose(A) {
<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:
});
});
});
});
}</lang>
}</syntaxhighlight>


=={{header|Stata}}==
=={{header|Stata}}==
Line 4,437: Line 4,437:


=== Stata matrices ===
=== Stata matrices ===
<lang stata>. mat a=1,2,3\4,5,6
<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</lang>
c3 3 6</syntaxhighlight>


=== Mata ===
=== Mata ===
<lang stata>: a=1,1i
<syntaxhighlight lang="stata">: a=1,1i


: a
: a
Line 4,475: Line 4,475:
1 | 1 |
1 | 1 |
2 | 1i |
2 | 1i |
+------+</lang>
+------+</syntaxhighlight>


=={{header|Swift}}==
=={{header|Swift}}==


<lang swift>@inlinable
<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)</lang>
printMatrix(m2)</syntaxhighlight>


{{out}}
{{out}}
Line 4,541: Line 4,541:


=={{header|Tailspin}}==
=={{header|Tailspin}}==
<lang 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:
<lang tcl>package require Tcl 8.5
<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"</lang>
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}}
<lang tcl>package require 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</lang>
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}}==
<lang qbasic>OPTION BASE 0
<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</lang>
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.
<lang Ursala>#cast %eLL
<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.>></lang>
<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}}==
<lang vb>Function transpose(m As Variant) As Variant
<syntaxhighlight lang="vb">Function transpose(m As Variant) As Variant
transpose = WorksheetFunction.transpose(m)
transpose = WorksheetFunction.transpose(m)
End Function</lang>
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}}
<lang vb>Option Explicit
<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</lang>
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.
<lang wortel>@zipm [[1 2 3] [4 5 6] [7 8 9]]</lang>
<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}}
<lang ecmascript>import "/matrix" for Matrix
<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)</lang>
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.
<lang XPL0>proc Transpose(M, R, C, N); \Transpose matrix M to N
<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);
]</lang>
]</syntaxhighlight>


{{out}}
{{out}}
Line 4,955: Line 4,955:
=={{header|Yabasic}}==
=={{header|Yabasic}}==
{{trans|FreeBASIC}}
{{trans|FreeBASIC}}
<lang yabasic>dim matriz(4,5)
<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</lang>
data 39,68,27,64,29</syntaxhighlight>




=={{header|zkl}}==
=={{header|zkl}}==
Using the GNU Scientific Library:
Using the GNU Scientific Library:
<lang zkl>var [const] GSL=Import("zklGSL"); // libGSL (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</lang>
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}}
<lang zkl>fcn transpose(M){
<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));
}</lang>
}</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.
<lang zkl>m:=T(T(1,2,3),T(4,5,6)); transpose(m).println();
<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();</lang>
transpose(L(L(1))).println();</syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>
Line 5,023: Line 5,023:


=={{header|zonnon}}==
=={{header|zonnon}}==
<lang zonnon>
<syntaxhighlight lang="zonnon">
module MatrixOps;
module MatrixOps;
type
type
Line 5,053: Line 5,053:
Transposition;
Transposition;
end MatrixOps.
end MatrixOps.
</syntaxhighlight>
</lang>