Matrix transposition: Difference between revisions

(→‎{{header|Wren}}: Minor tidy)
 
(39 intermediate revisions by 23 users not shown)
Line 3:
<br><br>
=={{header|11l}}==
<langsyntaxhighlight lang="11l">F transpose(&matrix)
V toRet = [[0] * matrix.len] * matrix[0].len
L(row) (0 .< matrix.len)
Line 14:
print(m)
print("After Transposition")
print(transpose(&m))</langsyntaxhighlight>
{{out}}
<pre>
Line 23:
</pre>
=={{header|360 Assembly}}==
<langsyntaxhighlight lang="360asm">...
KN EQU 3
KM EQU 5
Line 61:
B LOOPI next i
ELOOPI EQU * out of loop i
...</langsyntaxhighlight>
 
=={{header|68000 Assembly}}==
 
<syntaxhighlight lang="68000devpac">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</syntaxhighlight>
 
=={{header|ACL2}}==
<langsyntaxhighlight Lisplang="lisp">(defun cons-each (xs xss)
(if (or (endp xs) (endp xss))
nil
Line 80 ⟶ 111:
(list-each (first xss))
(cons-each (first xss)
(transpose-list (rest xss)))))</langsyntaxhighlight>
 
=={{header|Action!}}==
<syntaxhighlight lang="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</syntaxhighlight>
{{out}}
[https://gitlab.com/amarok8bit/action-rosetta-code/-/raw/master/images/Matrix_transposition.png Screenshot from Atari 8-bit computer]
<pre>
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
</pre>
 
=={{header|ActionScript}}==
In ActionScript, multi-dimensional arrays are created by making an "Array of arrays" where each element is an array.
<langsyntaxhighlight ActionScriptlang="actionscript">function transpose( m:Array):Array
{
//Assume each element in m is an array. (If this were production code, use typeof to be sure)
Line 106 ⟶ 225:
var M:Array = transpose(m);
for(var i:uint = 0; i < M.length; i++)
trace(M[i]);</langsyntaxhighlight>
 
=={{header|Ada}}==
Line 112 ⟶ 231:
 
This example illustrates use of Transpose for the matrices built upon the standard type Float:
<langsyntaxhighlight lang="ada">with Ada.Numerics.Real_Arrays; use Ada.Numerics.Real_Arrays;
with Ada.Text_IO; use Ada.Text_IO;
Line 138 ⟶ 257:
Put_Line ("After Transposition:");
Put (Transpose (Matrix));
end Matrix_Transpose;</langsyntaxhighlight>
{{out}}
<pre>
Line 154 ⟶ 273:
 
=={{header|Agda}}==
<langsyntaxhighlight lang="agda">module Matrix where
 
open import Data.Nat
Line 167 ⟶ 286:
 
a = (1 ∷ 2 ∷ 3 ∷ []) ∷ (4 ∷ 5 ∷ 6 ∷ []) ∷ []
b = transpose a</langsyntaxhighlight>
 
'''b''' evaluates to the following normal form:
 
<langsyntaxhighlight lang="agda">(1 ∷ 4 ∷ []) ∷ (2 ∷ 5 ∷ []) ∷ (3 ∷ 6 ∷ []) ∷ []</langsyntaxhighlight>
 
=={{header|ALGOL 68}}==
Line 178 ⟶ 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]}}
{{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}}
<langsyntaxhighlight lang="algol68">main:(
 
[,]REAL m=((1, 1, 1, 1),
Line 204 ⟶ 323:
printf(($x"Transpose:"l$));
pprint((ZIP m))
)</langsyntaxhighlight>
{{out}}
<pre>
 
Transpose:
(( 1.00, 2.00, 3.00, 4.00, 5.00),
Line 212 ⟶ 332:
( 1.00, 8.00, 27.00, 64.00,125.00),
( 1.00, 16.00, 81.00,256.00,625.00));
</pre>
=={{header|Amazing Hopper}}==
<syntaxhighlight lang="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
</syntaxhighlight>
{{out}}
<pre>
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
 
</pre>
 
=={{header|APL}}==
If M is a matrix, ⍉M is its transpose. For example,
<langsyntaxhighlight lang="apl">
3 3⍴⍳10
1 2 3
Line 225 ⟶ 409:
2 5 8
3 6 9
</syntaxhighlight>
</lang>
 
=={{header|AppleScript}}==
Line 231 ⟶ 415:
We can do this iteratively, by manually setting up two nested loops, and initialising iterators and empty lists,
 
<langsyntaxhighlight lang="applescript">on run
transpose([[1, 2, 3], [4, 5, 6], [7, 8, 9], [10, 11, 12]])
 
Line 251 ⟶ 435:
return lstTrans
end transpose</langsyntaxhighlight>
 
 
Line 258 ⟶ 442:
{{trans|JavaScript}}
 
<langsyntaxhighlight lang="applescript">-- TRANSPOSE ------------------------------------------ TRANSPOSE -----------------------
 
-- transpose :: [[a]] -> [[a]]
Line 278 ⟶ 462:
 
 
-- TEST --------------------------------------------- TEST -------------------------
on run
transpose([[1, 2, 3], [4, 5, 6], [7, 8, 9], [10, 11, 12]])
Line 285 ⟶ 469:
end run
 
 
-- GENERIC FUNCTIONS ---------------------------------------------------------
-------------------- GENERIC FUNCTIONS -------------------
 
-- map :: (a -> b) -> [a] -> [b]
Line 309 ⟶ 494:
end script
end if
end mReturn</langsyntaxhighlight>
 
{{Out}}
<langsyntaxhighlight AppleScriptlang="applescript">{{1, 4, 7, 10}, {2, 5, 8, 11}, {3, 6, 9, 12}}</langsyntaxhighlight>
 
=={{header|Arturo}}==
 
<langsyntaxhighlight lang="rebol">transpose: function [a][
X: size a
Y: size first a
Line 337 ⟶ 522:
loop arr 'row -> print row
print "-------------"
loop transpose arr 'row -> print row</langsyntaxhighlight>
 
{{out}}
Line 352 ⟶ 537:
 
=={{header|AutoHotkey}}==
<syntaxhighlight lang="autohotkey">a = a
<lang AutoHotkey>a = a
m = 10
n = 10
Line 410 ⟶ 595:
Return matrix
}
</syntaxhighlight>
</lang>
===Using Objects===
<langsyntaxhighlight AutoHotkeylang="autohotkey">Transpose(M){
R := []
for i, row in M
Line 418 ⟶ 603:
R[j,i] := col
return R
}</langsyntaxhighlight>
Examples:<langsyntaxhighlight AutoHotkeylang="autohotkey">Matrix := [[1,2,3],[4,5,6],[7,8,9],[10,11,12]]
MsgBox % ""
. "Original Matrix :`n" Print(Matrix)
Line 429 ⟶ 614:
Res .= (A_Index=1?"":"`t") col (Mod(A_Index,M[1].MaxIndex())?"":"`n")
return Trim(Res,"`n")
}</langsyntaxhighlight>
{{out}}
<pre>Original Matrix :
Line 444 ⟶ 629:
 
=={{header|AWK}}==
<syntaxhighlight lang="awk">
<lang AWK>
# syntax: GAWK -f MATRIX_TRANSPOSITION.AWK filename
{ if (NF > nf) {
Line 459 ⟶ 644:
exit(0)
}
</syntaxhighlight>
</lang>
<p>input:</p>
<pre>
Line 474 ⟶ 659:
</pre>
===Using 2D-Arrays===
<langsyntaxhighlight AWKlang="awk"># Usage: GAWK -f MATRIX_TRANSPOSITION.AWK filename
{
i = NR
Line 502 ⟶ 687:
function max(m, n) {
return m > n ? m : n
}</langsyntaxhighlight>
<p><b>Input:</b></p>
<pre>
Line 544 ⟶ 729:
PRINT
NEXT rows
 
 
=={{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 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</syntaxhighlight>
 
 
=={{header|BBC BASIC}}==
{{works with|BBC BASIC for Windows}}
<langsyntaxhighlight lang="bbcbasic"> INSTALL @lib$+"ARRAYLIB"
DIM matrix(3,4), transpose(4,3)
Line 568 ⟶ 777:
NEXT
PRINT
NEXT row%</langsyntaxhighlight>
{{out}}
<pre>
Line 582 ⟶ 791:
36 50 10 29
</pre>
 
 
=={{header|BQN}}==
{{trans|APL}}
If M is a matrix, ⍉M is its transpose. For example,
<syntaxhighlight lang="bqn">
3‿3⥊↕9
┌─
╵ 0 1 2
3 4 5
6 7 8
⍉3‿3⥊↕9
┌─
╵ 0 3 6
1 4 7
2 5 8
</syntaxhighlight>
 
=={{header|Burlesque}}==
 
<langsyntaxhighlight lang="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
Line 592 ⟶ 820:
12 42 78 64
36 50 10 29
</syntaxhighlight>
</lang>
 
=={{header|C}}==
Transpose a 2D double array.
<langsyntaxhighlight lang="c">#include <stdio.h>
 
void transpose(void *dest, void *src, int src_h, int src_w)
Line 620 ⟶ 848:
printf("%g%c", b[i][j], j == 2 ? '\n' : ' ');
return 0;
}</langsyntaxhighlight>
 
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.
<langsyntaxhighlight lang="c">#include <stdio.h>
 
void transpose(double *m, int w, int h)
Line 672 ⟶ 900:
 
return 0;
}</langsyntaxhighlight>
{{out}}
<pre>
Line 688 ⟶ 916:
 
=={{header|C sharp|C#}}==
<langsyntaxhighlight lang="csharp">using System;
using System.Text;
 
Line 719 ⟶ 947:
}
}
}</langsyntaxhighlight>
 
=={{header|C++}}==
Line 725 ⟶ 953:
 
{{libheader|Boost.uBLAS}}
<langsyntaxhighlight lang="cpp">#include <boost/numeric/ublas/matrix.hpp>
#include <boost/numeric/ublas/io.hpp>
 
Line 739 ⟶ 967:
 
std::cout << trans(m) << std::endl;
}</langsyntaxhighlight>
 
{{out}}
Line 748 ⟶ 976:
===Generic solution===
;main.cpp
<langsyntaxhighlight lang="cpp">#include <iostream>
#include "matrix.h"
 
Line 786 ⟶ 1,014:
}
 
} /* main() */</langsyntaxhighlight>
;matrix.h
<langsyntaxhighlight lang="cpp">#ifndef _MATRIX_H
#define _MATRIX_H
 
Line 982 ⟶ 1,210:
}
 
#endif /* _MATRIX_H */</langsyntaxhighlight>
 
{{out}}
Line 997 ⟶ 1,225:
 
===Easy Mode===
<langsyntaxhighlight lang="cpp">#include <iostream>
 
int main(){
Line 1,032 ⟶ 1,260:
return 0;
}</langsyntaxhighlight>
{{out}}
<pre>
Line 1,049 ⟶ 1,277:
 
=={{header|Clojure}}==
<langsyntaxhighlight lang="lisp">(defmulti matrix-transpose
"Switch rows with columns."
class)
Line 1,060 ⟶ 1,288:
[mtx]
(apply mapv vector mtx))
</syntaxhighlight>
</lang>
{{out}}
<pre>=> (matrix-transpose [[1 2 3] [4 5 6]])
Line 1,066 ⟶ 1,294:
 
=={{header|CoffeeScript}}==
<langsyntaxhighlight lang="coffeescript">transpose = (matrix) ->
(t[i] for t in matrix) for i in [0...matrix[0].length]</langsyntaxhighlight>
{{out}}
<pre>
Line 1,077 ⟶ 1,305:
=={{header|Common Lisp}}==
If the matrix is given as a list:
<langsyntaxhighlight lang="lisp">(defun transpose (m)
(apply #'mapcar #'list m))</langsyntaxhighlight>
 
If the matrix A is given as a 2D array:
<langsyntaxhighlight lang="lisp">;; Transpose a mxn matrix A to a nxm matrix B=A'.
(defun mtp (A)
(let* ((m (array-dimension A 0))
Line 1,090 ⟶ 1,318:
(setf (aref B j i)
(aref A i j))))
B))</langsyntaxhighlight>
 
=={{header|D}}==
===Standard Version===
<langsyntaxhighlight lang="d">void main() {
import std.stdio, std.range;
 
Line 1,101 ⟶ 1,329:
[18, 19, 20, 21]];
writefln("%(%(%2d %)\n%)", M.transposed);
}</langsyntaxhighlight>
{{out}}
<pre>10 14 18
Line 1,109 ⟶ 1,337:
 
===Locally Procedural Style===
<langsyntaxhighlight lang="d">T[][] transpose(T)(in T[][] m) pure nothrow {
auto r = new typeof(return)(m[0].length, m.length);
foreach (immutable nr, const row; m)
Line 1,124 ⟶ 1,352:
[18, 19, 20, 21]];
writefln("%(%(%2d %)\n%)", M.transpose);
}</langsyntaxhighlight>
Same output.
 
===Functional Style===
<langsyntaxhighlight lang="d">import std.stdio, std.algorithm, std.range, std.functional;
 
auto transpose(T)(in T[][] m) pure nothrow {
Line 1,139 ⟶ 1,367:
[18, 19, 20, 21]];
writefln("%(%(%2d %)\n%)", M.transpose);
}</langsyntaxhighlight>
Same output.
=={{header|Delphi}}==
See [[#Pascal]];
=={{header|EasyLang}}==
<syntaxhighlight lang="easylang">
proc transpose . m[][] .
len n[][] len m[1][]
for i to len n[][]
for j to len m[][]
n[i][] &= m[j][i]
.
.
swap n[][] m[][]
.
m[][] = [ [ 1 2 3 4 ] [ 5 6 7 8 ] [ 9 10 11 12 ] ]
print m[][]
print ""
transpose m[][]
print m[][]
</syntaxhighlight>
{{out}}
<pre>
[
[ 1 2 3 4 ]
[ 5 6 7 8 ]
[ 9 10 11 12 ]
]
 
[
[ 1 5 9 ]
[ 2 6 10 ]
[ 3 7 11 ]
[ 4 8 12 ]
]
</pre>
 
=={{header|EchoLisp}}==
<langsyntaxhighlight lang="scheme">
(lib 'matrix)
 
Line 1,155 ⟶ 1,416:
0 2 4
1 3 5
</syntaxhighlight>
</lang>
 
=={{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.
===Create a new matrix===
<langsyntaxhighlight lang="edsac">
[Demo of matrix transposition. Not in place, creates a new matrix.
EDSAC, Initial Orders 2.]
Line 1,273 ⟶ 1,534:
E12Z [enter at 12 (relative)]
PF [accumulator = 0 on entry]
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 1,289 ⟶ 1,550:
{{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.
<langsyntaxhighlight lang="edsac">
[Transpose a matrix in place. EDSAC, Initial Orders 2.]
..PZ [blank tape and terminator]
Line 1,379 ⟶ 1,640:
T10@A9@A8@U9@TFA23@A2FT23@A10@A2FG19@A3@T10FA4@T11FA5@T12FA6@T13F
A38@GMO1@O2@A42@GXA10FTFA11FT10FAFT11FA50@GMO@ZFE11ZPF
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 1,397 ⟶ 1,658:
 
=={{header|Elixir}}==
<langsyntaxhighlight lang="elixir">m = [[1, 1, 1, 1],
[2, 4, 8, 16],
[3, 9, 27, 81],
Line 1,405 ⟶ 1,666:
transpose = fn(m)-> List.zip(m) |> Enum.map(&Tuple.to_list(&1)) end
 
IO.inspect transpose.(m)</langsyntaxhighlight>
 
{{out}}
Line 1,415 ⟶ 1,676:
Sample originally from ftp://ftp.dra.hmg.gb/pub/ella (a now dead link) - Public release.
 
Code for matrix transpose hardware design verification:<langsyntaxhighlight 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].</langsyntaxhighlight>
 
=={{header|Emacs Lisp}}==
 
<lang lisp>
{{libheader|cl-lib}}
 
<syntaxhighlight lang="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)))</syntaxhighlight>
</lang>
 
{{out}}
Line 1,433 ⟶ 1,697:
(4 6 9)
(5 9 9))
</pre>
 
Implementation using seq library:
 
<syntaxhighlight lang="lisp">
(defun matrix-transposition (m)
(apply #'seq-mapn (append (list #'list) m)) )
 
(let ((m '(( 2 0 -5 -1)
(-3 -2 -4 7)
(-1 -3 0 -6))))
(message "%s" (matrix-transposition m)) )
</syntaxhighlight>
 
{{out}}
 
<pre>
((2 -3 -1) (0 -2 -3) (-5 -4 0) (-1 7 -6))
</pre>
 
Line 1,439 ⟶ 1,721:
A nice introduction http://langintro.com/erlang/article2/ which is much more explicit.
 
<langsyntaxhighlight lang="erlang">
-module(transmatrix).
-export([trans/1,transL/1]).
Line 1,458 ⟶ 1,740:
transL([ [] | List] ) -> transL(List);
transL([]) -> [].
</syntaxhighlight>
</lang>
 
{{out}}
Line 1,471 ⟶ 1,753:
 
=={{header|Euphoria}}==
<langsyntaxhighlight lang="euphoria">function transpose(sequence in)
sequence out
out = repeat(repeat(0,length(in)),length(in[1]))
Line 1,489 ⟶ 1,771:
}
 
? transpose(m)</langsyntaxhighlight>
 
{{out}}
Line 1,572 ⟶ 1,854:
=={{header|F_Sharp|F#}}==
Very straightforward solution...
<langsyntaxhighlight lang="fsharp">let transpose (mtx : _ [,]) = Array2D.init (mtx.GetLength 1) (mtx.GetLength 0) (fun x y -> mtx.[y,x])</langsyntaxhighlight>
 
=={{header|Factor}}==
<code>flip</code> can be used.
<langsyntaxhighlight lang="factor">( scratchpad ) { { 1 2 3 } { 4 5 6 } } flip .
{ { 1 4 } { 2 5 } { 3 6 } }</langsyntaxhighlight>
 
=={{header|Fermat}}==
Matrix transpose is built in.
<syntaxhighlight lang="fermat">
Array a[3,1]
[a]:=[(1,2,3)]
[b]:=Trans([a])
[a]
[b]
</syntaxhighlight>
{{out}}
<pre>
[[ 1, `
2, `
3 ]]
 
[[ 1, 2, 3 ]]</pre>
 
=={{header|Forth}}==
{{libheader|Forth Scientific Library}}
{{works with|gforth|0.7.9_20170308}}
<langsyntaxhighlight lang="forth">S" fsl-util.fs" REQUIRED
S" fsl/dynmem.seq" REQUIRED
: F+! ( addr -- ) ( F: r -- ) DUP F@ F+ F! ;
Line 1,593 ⟶ 1,892:
 
a{{ 5 3 & b{{ transpose
3 5 b{{ }}fprint</langsyntaxhighlight>
 
=={{header|Fortran}}==
In ISO Fortran 90 or later, use the TRANSPOSE intrinsic function:
<langsyntaxhighlight lang="fortran">integer, parameter :: n = 3, m = 5
real, dimension(n,m) :: a = reshape( (/ (i,i=1,n*m) /), (/ n, m /) )
real, dimension(m,n) :: b
Line 1,609 ⟶ 1,908:
do j = 1, m
print *, b(j,:)
end do</langsyntaxhighlight>
 
In ANSI FORTRAN 77 with MIL-STD-1753 extensions or later, use nested structured DO loops:
<langsyntaxhighlight 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/
 
Line 1,619 ⟶ 1,918:
B(J,I) = A(I,J)
END DO
END DO</langsyntaxhighlight>
 
In ANSI FORTRAN 66 or later, use nested labeled DO loops:
<langsyntaxhighlight 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/
Line 1,629 ⟶ 1,928:
B(J,I) = A(I,J)
20 CONTINUE
10 CONTINUE</langsyntaxhighlight>
 
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 <langsyntaxhighlight Fortranlang="fortran"> DIMENSION A(3,5),B(5,3),C(5,3)
EQUIVALENCE (A,C) !Occupy the same storage.
DATA A/
Line 1,658 ⟶ 1,957:
1 FORMAT (5F6.1) !Five values per line.
2 FORMAT (3F6.1) !Three values per line.
END</langsyntaxhighlight>
 
Output:
Line 1,694 ⟶ 1,993:
 
=={{header|FreeBASIC}}==
<langsyntaxhighlight lang="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},_
Line 1,716 ⟶ 2,015:
Print
Next fila
Sleep</langsyntaxhighlight>
{{out}}
<pre>
Line 1,734 ⟶ 2,033:
=={{header|Frink}}==
The built-in array method <CODE>transpose</CODE> transposes a 2-dimensional array.
<langsyntaxhighlight lang="frink">
a = [[1,2,3],
[4,5,6],
[7,8,9]]
joinjoinln["\n",a.transpose[]]
</syntaxhighlight>
</lang>
 
=={{header|Fōrmulæ}}==
 
In [http{{FormulaeEntry|page=https://wiki.formulae.org/?script=examples/Matrix_transposition this] page you can see the solution of this task.}}
 
'''Solution'''
Fōrmulæ programs are not textual, visualization/edition of programs is done showing/manipulating structures but not text ([http://wiki.formulae.org/Editing_F%C5%8Drmul%C3%A6_expressions more info]). Moreover, there can be multiple visual representations of the same program. Even though it is possible to have textual representation &mdash;i.e. XML, JSON&mdash; they are intended for transportation effects more than visualization and edition.
 
Matrix transposition is an intrsinec operation in Fōrmulæ, through the Transpose expression:
The option to show Fōrmulæ programs and their results is showing images. Unfortunately images cannot be uploaded in Rosetta Code.
 
[[File:Fōrmulæ - Matrix transposition 01.png]]
 
[[File:Fōrmulæ - Matrix transposition 02.png]]
 
However, a matrix transposition can be coded:
 
[[File:Fōrmulæ - Matrix transposition 03.png]]
 
[[File:Fōrmulæ - Matrix transposition 04.png]]
 
[[File:Fōrmulæ - Matrix transposition 02.png]]
 
=={{header|GAP}}==
<langsyntaxhighlight lang="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);</langsyntaxhighlight>
 
=={{header|Go}}==
===Library gonum/mat===
<langsyntaxhighlight lang="go">package main
 
import (
Line 1,775 ⟶ 2,086:
fmt.Println()
fmt.Println(mat.Formatted(m.T()))
}</langsyntaxhighlight>
{{out}}
<pre>
Line 1,787 ⟶ 2,098:
 
===Library go.matrix===
<langsyntaxhighlight lang="go">package main
 
import (
Line 1,805 ⟶ 2,116:
fmt.Println("transpose:")
fmt.Println(m)
}</langsyntaxhighlight>
{{out}}
<pre>
Line 1,819 ⟶ 2,130:
===2D representation===
Go arrays and slices are only one-dimensional. The obvious way to represent two-dimensional arrays is with a slice of slices:
<langsyntaxhighlight lang="go">package main
 
import "fmt"
Line 1,853 ⟶ 2,164:
}
return r
}</langsyntaxhighlight>
{{out}}
<pre>[1 2 3]
Line 1,864 ⟶ 2,175:
 
A flat element representation with a stride is almost always better.
<langsyntaxhighlight lang="go">package main
 
import "fmt"
Line 1,914 ⟶ 2,225:
}
return r
}</langsyntaxhighlight>
{{out}}
<pre>
Line 1,929 ⟶ 2,240:
{{trans|C}}
Note representation is "flat," as above, but without the fluff of constructing from rows.
<langsyntaxhighlight lang="go">package main
 
import "fmt"
Line 1,989 ⟶ 2,300:
}
m.stride = h
}</langsyntaxhighlight>
Output same as above.
 
=={{header|Groovy}}==
The Groovy extensions to the List class provides a transpose method:
<langsyntaxhighlight lang="groovy">def matrix = [ [ 1, 2, 3, 4 ],
[ 5, 6, 7, 8 ] ]
 
Line 2,001 ⟶ 2,312:
def transpose = matrix.transpose()
 
transpose.each { println it }</langsyntaxhighlight>
 
{{out}}
Line 2,014 ⟶ 2,325:
=={{header|Haskell}}==
For matrices represented as lists, there's ''transpose'':
<langsyntaxhighlight lang="haskell">*Main> transpose [[1,2],[3,4],[5,6]]
[[1,3,5],[2,4,6]]</langsyntaxhighlight>
 
For matrices in arrays, one can use ''ixmap'':
<langsyntaxhighlight lang="haskell">import Data.Array
 
swap (x,y) = (y,x)
Line 2,024 ⟶ 2,335:
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</langsyntaxhighlight>
 
Using ''zipWith'' assuming a matrix is a list of row lists:
<langsyntaxhighlight lang="haskell">
tpose [ms] = [[m] | m <- ms]
tpose (ms:mss) = zipWith (:) ms (tpose mss)
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 2,036 ⟶ 2,347:
[[1,4,7],[2,5,8],[3,6,9]]
</pre>
 
or, in terms of Data.Matrix:
 
<syntaxhighlight lang="haskell">import Data.Matrix
 
main :: IO ()
main = print matrix >> print (transpose matrix)
where
matrix = fromList 3 4 [1 ..]</syntaxhighlight>
{{Out}}
<pre>┌ ┐
│ 1 2 3 4 │
│ 5 6 7 8 │
│ 9 10 11 12 │
└ ┘
┌ ┐
│ 1 5 9 │
│ 2 6 10 │
│ 3 7 11 │
│ 4 8 12 │
└ ┘</pre>
 
===With Numeric.LinearAlgebra===
<langsyntaxhighlight lang="haskell">import Numeric.LinearAlgebra
 
a :: Matrix I
Line 2,048 ⟶ 2,380:
main = do
print $ a
print $ tr a</langsyntaxhighlight>
{{out}}
<pre>(3><2)
Line 2,059 ⟶ 2,391:
 
=={{header|Haxe}}==
<langsyntaxhighlight lang="haxe">class Matrix {
static function main() {
var m = [ [1, 1, 1, 1],
Line 2,075 ⟶ 2,407:
for(a in aa) Sys.println(a);
}
}</langsyntaxhighlight>
{{Out}}
<pre>[1,1,1,1]
Line 2,088 ⟶ 2,420:
 
=={{header|HicEst}}==
<langsyntaxhighlight lang="hicest">REAL :: mtx(2, 4)
 
mtx = 1.1 * $
Line 2,094 ⟶ 2,426:
 
SOLVE(Matrix=mtx, Transpose=mtx)
WRITE() mtx</langsyntaxhighlight>
{{out}}
<pre>1.1 2.2 3.3 4.4
Line 2,105 ⟶ 2,437:
 
=={{header|Hope}}==
<langsyntaxhighlight lang="hope">uses lists;
dec transpose : list (list alpha) -> list (list alpha);
--- transpose ([]::_) <= [];
--- transpose n <= map head n :: transpose (map tail n);</langsyntaxhighlight>
 
=={{header|Icon}} and {{header|Unicon}}==
<langsyntaxhighlight Iconlang="icon">procedure transpose_matrix (matrix)
result := []
# for each column
Line 2,138 ⟶ 2,470:
write ("Transposed:")
print_matrix (transposed)
end</langsyntaxhighlight>
{{out}}
<pre>
Line 2,152 ⟶ 2,484:
=={{header|IDL}}==
Standard IDL function <tt>transpose()</tt>
<langsyntaxhighlight lang="idl">m=[[1,1,1,1],[2, 4, 8, 16],[3, 9,27, 81],[5, 25,125, 625]]
print,transpose(m)</langsyntaxhighlight>
 
=={{header|Idris}}==
<langsyntaxhighlight lang="idris">Idris> transpose [[1,2],[3,4],[5,6]]
[[1, 3, 5], [2, 4, 6]] : List (List Integer)</langsyntaxhighlight>
 
=={{Header|Insitux}}==
 
<syntaxhighlight lang="insitux">
(var transpose2d @(... map vec))
 
(transpose2d [[1 1 1 1] [2 4 8 16] [3 9 27 81] [4 16 64 256] [5 25 125 625]])
</syntaxhighlight>
 
{{out}}
 
<pre>
[[1 2 3 4 5] [1 4 9 16 25] [1 8 27 64 125] [1 16 81 256 625]]
</pre>
 
=={{header|J}}==
Line 2,164 ⟶ 2,510:
 
'''Example:'''
<langsyntaxhighlight lang="j"> ]matrix=: (^/ }:) >:i.5 NB. make and show example matrix
1 1 1 1
2 4 8 16
Line 2,174 ⟶ 2,520:
1 4 9 16 25
1 8 27 64 125
1 16 81 256 625</langsyntaxhighlight>
 
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}}==
<langsyntaxhighlight lang="java">import java.util.Arrays;
public class Transpose{
public static void main(String[] args){
Line 2,197 ⟶ 2,543:
}
}
}</langsyntaxhighlight>
 
=={{header|JavaScript}}==
===ES5===
{{works with|SpiderMonkey}} for the <code>print()</code> function
<langsyntaxhighlight lang="javascript">function Matrix(ary) {
this.mtx = ary
this.height = ary.length;
Line 2,230 ⟶ 2,576:
print(m);
print();
print(m.transpose());</langsyntaxhighlight>
 
produces
Line 2,246 ⟶ 2,592:
 
Or, as a functional expression (rather than an imperative procedure):
<langsyntaxhighlight lang="javascript">
(function () {
'use strict';
Line 2,263 ⟶ 2,609:
 
})();
</syntaxhighlight>
</lang>
 
{{Out}}
Line 2,271 ⟶ 2,617:
===ES6===
 
<langsyntaxhighlight JavaScriptlang="javascript">(() => {
"use strict";
 
Line 2,298 ⟶ 2,644:
// MAIN ---
return main();
})();</langsyntaxhighlight>
{{Out}}
<langsyntaxhighlight JavaScriptlang="javascript">[[1,4,7],[2,5,8],[3,6,9]]</langsyntaxhighlight>
 
=={{header|Joy}}==
For matrices represented as lists, there's ''transpose'', defined in seqlib like this:
<langsyntaxhighlight lang="joy">DEFINE transpose == [ [null] [true] [[null] some] ifte ]
[ pop [] ]
[ [[first] map] [[rest] map] cleave ]
[ cons ]
linrec .</langsyntaxhighlight>
 
=={{header|jq}}==
Line 2,315 ⟶ 2,661:
 
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.
<langsyntaxhighlight lang="jq">def transpose:
if (.[0] | length) == 0 then []
else [map(.[0])] + (map(.[1:]) | transpose)
end ;</langsyntaxhighlight>
'''Examples'''
[[], []] | transpose
Line 2,334 ⟶ 2,680:
First a module, shared by the Transposition, Multiplication and Exponentiation tasks.
 
<langsyntaxhighlight lang="javascript">/* Matrix transposition, multiplication, identity, and exponentiation, in Jsish */
function Matrix(ary) {
this.mtx = ary;
Line 2,392 ⟶ 2,738:
};
 
provide('Matrix', '0.60');</langsyntaxhighlight>
 
Then a unitTest of the transposition.
 
<langsyntaxhighlight lang="javascript">/* Matrix transposition, in Jsish */
require('Matrix');
 
Line 2,410 ⟶ 2,756:
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!=
*/</langsyntaxhighlight>
 
{{out}}
Line 2,418 ⟶ 2,764:
=={{header|Julia}}==
The transposition is obtained by quoting the matrix.
<langsyntaxhighlight Julialang="julia">julia> [1 2 3 ; 4 5 6] # a 2x3 matrix
2x3 Array{Int64,2}:
1 2 3
Line 2,427 ⟶ 2,773:
1 4
2 5
3 6</langsyntaxhighlight>
 
If you do not want change the type, convert the result back to Array{Int64,2}.
Line 2,433 ⟶ 2,779:
=={{header|K}}==
Transpose is the monadic verb <code>+</code>
<langsyntaxhighlight lang="k"> {x^\:-1_ x}1+!:5
(1 1 1 1.0
2 4 8 16.0
Line 2,444 ⟶ 2,790:
1 4 9 16 25.0
1 8 27 64 125.0
1 16 81 256 625.0)</langsyntaxhighlight>
 
=={{header|Klong}}==
Transpose is the monadic verb <code>+</code>
<langsyntaxhighlight lang="k"> [5 5]:^!25
[[0 1 2 3 4]
[5 6 7 8 9]
Line 2,460 ⟶ 2,806:
[2 7 12 17 22]
[3 8 13 18 23]
[4 9 14 19 24]]</langsyntaxhighlight>
 
=={{header|Kotlin}}==
<langsyntaxhighlight lang="scala">// version 1.1.3
 
typealias Vector = DoubleArray
Line 2,478 ⟶ 2,824:
}
 
// Alternate version
fun printMatrix(m: Matrix) {
typealias Matrix<T> = List<List<T>>
for (i in 0 until m.size) println(m[i].contentToString())
fun <T> Matrix<T>.transpose(): Matrix<T> {
}
return (0 until this[0].size).map { x ->
(this.indices).map { y ->
this[y][x]
}
}
}</syntaxhighlight>
 
fun main(args: Array<String>) {
val m = arrayOf(
doubleArrayOf( 1.0, 2.0, 3.0),
doubleArrayOf( 4.0, 5.0, 6.0),
doubleArrayOf( 7.0, 8.0, 9.0),
doubleArrayOf(10.0, 11.0, 12.0)
)
printMatrix(m.transpose())
}</lang>
 
=={{header|Lambdatalk}}==
{{out}}
 
<pre>
<syntaxhighlight lang="scheme">
[1.0, 4.0, 7.0, 10.0]
{require lib_matrix}
[2.0, 5.0, 8.0, 11.0]
 
[3.0, 6.0, 9.0, 12.0]
{M.disp
</pre>
{M.transp
[[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]]
 
</syntaxhighlight>
 
=={{header|Lang5}}==
<langsyntaxhighlight Lang5lang="lang5">12 iota [3 4] reshape 1 + dup .
1 transpose .</langsyntaxhighlight>
{{out}}
<pre>[
Line 2,516 ⟶ 2,873:
=={{header|LFE}}==
 
<langsyntaxhighlight lang="lisp">
(defun transpose (matrix)
(transpose matrix '()))
Line 2,530 ⟶ 2,887:
(tails (lists:map #'cdr/1 matrix)))
(transpose tails (++ acc `(,heads)))))))
</syntaxhighlight>
</lang>
 
Usage in the LFE REPL:
 
<langsyntaxhighlight lang="lisp">
> (transpose '((1 2 3)
(4 5 6)
Line 2,543 ⟶ 2,900:
((1 4 7 10 13 16) (2 5 8 11 14 17) (3 6 9 12 15 18))
>
</syntaxhighlight>
</lang>
 
=={{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.
<langsyntaxhighlight 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"
Line 2,553 ⟶ 2,910:
print " ="
MatrixT$ =MatrixTranspose$( MatrixC$)
call DisplayMatrix MatrixT$</langsyntaxhighlight>
 
{{out}}
Line 2,568 ⟶ 2,925:
 
=={{header|Lua}}==
<langsyntaxhighlight lang="lua">function Transpose( m )
local res = {}
Line 2,590 ⟶ 2,947:
end
io.write( "\n" )
end</langsyntaxhighlight>
 
Using apply map list
<langsyntaxhighlight lang="lua">function map(f, a)
local b = {}
for k,v in ipairs(a) do b[k] = f(v) end
Line 2,619 ⟶ 2,976:
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"))</langsyntaxhighlight>
 
--Edit: table.getn() deprecated, using # instead
Line 2,627 ⟶ 2,984:
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>>;
 
Line 2,634 ⟶ 2,991:
with(LinearAlgebra):
Transpose(M);
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 2,655 ⟶ 3,012:
 
=={{header|Mathematica}}/{{header|Wolfram Language}}==
<langsyntaxhighlight lang="mathematica">originalMatrix = {{1, 1, 1, 1},
{2, 4, 8, 16},
{3, 9, 27, 81},
{4, 16, 64, 256},
{5, 25, 125, 625}}
transposedMatrix = Transpose[originalMatrix]</langsyntaxhighlight>
 
=={{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]].
<langsyntaxhighlight Matlablang="matlab">>> transpose([1 2;3 4])
 
ans =
Line 2,676 ⟶ 3,033:
 
1 3
2 4</langsyntaxhighlight>
 
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.
Line 2,688 ⟶ 3,045:
end
 
</syntaxhighlight>
</lang>
 
Transposing nested cells using apply map list
<langsyntaxhighlight Matlablang="matlab">xy = {{1,2,3,4},{1,2,3,4},{1,2,3,4}}
yx = feval(@(x) cellfun(@(varargin)[varargin],x{:},'un',0), xy)</langsyntaxhighlight>
 
=={{header|Maxima}}==
<langsyntaxhighlight lang="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);</langsyntaxhighlight>
 
=={{header|MAXScript}}==
Uses the built in transpose() function
<langsyntaxhighlight 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
m = transpose m</langsyntaxhighlight>
 
=={{header|Nial}}==
make an array
<langsyntaxhighlight lang="nial">|a := 2 3 reshape count 6
=1 2 3
=4 5 6</langsyntaxhighlight>
transpose it
<langsyntaxhighlight lang="nial">|transpose a
=1 4
=2 5
=3 6</langsyntaxhighlight>
 
=={{header|Nim}}==
For statically sized arrays:
<langsyntaxhighlight 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 j in low(Y)..high(Y):
Line 2,733 ⟶ 3,090:
for i in r:
stdout.write i, " "
echo ""</langsyntaxhighlight>
{{out}}
<pre> 0 5 1
Line 2,741 ⟶ 3,098:
4 9 42 </pre>
For dynamically sized seqs:
<langsyntaxhighlight lang="nim">proc transpose[T](s: seq[seq[T]]): seq[seq[T]] =
result = newSeq[seq[T]](s[0].len)
for i in 0 .. s[0].high:
Line 2,751 ⟶ 3,108:
@[ 5, 6, 7, 8, 9],
@[ 1, 0, 0, 0, 42]]
echo transpose(a)</langsyntaxhighlight>
{{out}}
<pre>@[@[0, 5, 1], @[1, 6, 0], @[2, 7, 0], @[3, 8, 0], @[4, 9, 42]]</pre>
 
=={{header|Objeck}}==
<langsyntaxhighlight lang="objeck">
bundle Default {
class Transpose {
Line 2,788 ⟶ 3,145:
}
}
</syntaxhighlight>
</lang>
 
{{out}}
Line 2,802 ⟶ 3,159:
The implementation below uses a bigarray:
 
<langsyntaxhighlight lang="ocaml">open Bigarray
 
let transpose b =
Line 2,831 ⟶ 3,188:
[| 5; 6; 7; 8 |];
|]
;;
 
array2_display (Printf.printf " %d") print_newline (transpose a) ;;</langsyntaxhighlight>
 
{{out}}
Line 2,842 ⟶ 3,200:
</pre>
A version for lists:
<langsyntaxhighlight lang="ocaml">let rec transpose m =
assert (m <> []);
if List.mem [] m then
[]
else
List.map List.hd m :: transpose (List.map List.tl m)</langsyntaxhighlight>
Example:
# transpose [[1;2;3;4];
Line 2,854 ⟶ 3,212:
 
=={{header|Octave}}==
<langsyntaxhighlight lang="octave">a = [ 1, 1, 1, 1 ;
2, 4, 8, 16 ;
3, 9, 27, 81 ;
Line 2,860 ⟶ 3,218:
5, 25, 125, 625 ];
tranposed = a.'; % tranpose
ctransp = a'; % conjugate transpose</langsyntaxhighlight>
 
=={{header|OxygenBasic}}==
<langsyntaxhighlight lang="oxygenbasic">
function Transpose(double *A,*B, sys nx,ny)
'==========================================
Line 2,906 ⟶ 3,264:
Transpose A,B,5,4
print MatrixShow B,4,5
</syntaxhighlight>
</lang>
 
=={{header|PARI/GP}}==
The GP function for matrix (or vector) transpose is <code>mattranspose</code>, but it is usually invoked with a tilde:
<syntaxhighlight lang ="parigp">M~</langsyntaxhighlight>
 
In PARI the function is
<syntaxhighlight lang C="c">gtrans(M)</langsyntaxhighlight>
though <code>shallowtrans</code> is also available when deep copying is not desired.
 
=={{header|Pascal}}==
<langsyntaxhighlight lang="pascal">Program Transpose;
 
const
Line 2,948 ⟶ 3,306:
writeln;
end;
end.</langsyntaxhighlight>
{{out}}
<pre>% ./Transpose
Line 2,965 ⟶ 3,323:
=={{header|Perl}}==
{{libheader|Math::Matrix}}
<langsyntaxhighlight lang="perl">use Math::Matrix;
 
$m = Math::Matrix->new(
Line 2,975 ⟶ 3,333:
);
 
$m->transpose->print;</langsyntaxhighlight>
 
{{out}}
Line 2,985 ⟶ 3,343:
</pre>
Manually:
<langsyntaxhighlight lang="perl">my @m = (
[1, 1, 1, 1],
[2, 4, 8, 16],
Line 2,996 ⟶ 3,354:
foreach my $j (0..$#{$m[0]}) {
push(@transposed, [map $_->[$j], @m]);
}</langsyntaxhighlight>
 
=={{header|Phix}}==
<!--<langsyntaxhighlight Phixlang="phix">(phixonline)-->
<span style="color: #008080;">functionwith</span> <span style="color: #000000008080;">transpose</span><span style="color: #0000FF;">(</span><span style="color: #004080;">sequence</span> <span style="color: #000000;">mat</span><span style="color: #0000FF;">)javascript_semantics</span>
<span style="color: #004080008080;">integerfunction</span> <span style="color: #000000;">nmatrix_transpose</span> <span style="color: #0000FF;">=(</span> <span style="color: #7060A8004080;">lengthsequence</span><span style="color: #0000FF;">(</span><span style="color: #000000;">mat</span><span style="color: #0000FF;">),</span>
<span style="color: #000000004080;">minteger</span> <span style="color: #0000FF000000;">=rows</span> <span style="color: #7060A80000FF;">length=</span><span style="color: #0000FF;">(</span><span style="color: #0000007060A8;">matlength</span><span style="color: #0000FF;">[(</span><span style="color: #000000;">1mat</span><span style="color: #0000FF;">]),</span>
<span style="color: #004080;">sequence</span> <span style="color: #000000;">res</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8000000;">repeatcols</span> <span style="color: #0000FF;">(=</span> <span style="color: #7060A8;">repeatlength</span><span style="color: #0000FF;">(</span><span style="color: #000000;">0</span><span style="color: #0000FF;">,</span><span style="color: #000000;">nmat</span><span style="color: #0000FF;">),[</span><span style="color: #000000;">m1</span><span style="color: #0000FF;">])</span>
<span style="color: #008080004080;">forsequence</span> <span style="color: #000000;">ires</span> <span style="color: #0000FF;">=</span> <span style="color: #0000007060A8;">1repeat</span><span style="color: #0000FF;">(</span><span style="color: #0080807060A8;">torepeat</span><span style="color: #0000FF;">(</span><span style="color: #000000;">n0</span><span style="color: #0000FF;">,</span><span style="color: #008080000000;">rows</span><span style="color: #0000FF;">),</span><span style="color: #000000;">cols</span><span style="color: #0000FF;">do)</span>
<span style="color: #008080;">for</span> <span style="color: #000000;">jr</span><span style="color: #0000FF;">=</span><span style="color: #000000;">1</span> <span style="color: #008080;">to</span> <span style="color: #000000;">mrows</span> <span style="color: #008080;">do</span>
<span style="color: #000000008080;">resfor</span><span style="color: #0000FF;">[</span><span style="color: #000000;">jc</span><span style="color: #0000FF;">][=</span><span style="color: #000000;">i</span><span style="color: #0000FF;">]1</span> <span style="color: #0000FF008080;">=to</span> <span style="color: #000000;">matcols</span><span style="color: #0000FF;">[</span><span style="color: #000000;">i</span><span style="color: #0000FF;">][</span><span style="color: #000000;">j</span><span style="color: #0000FF008080;">]do</span>
<span style="color: #000000;">res</span><span style="color: #0000FF;">[</span><span style="color: #000000;">c</span><span style="color: #0000FF;">][</span><span style="color: #000000;">r</span><span style="color: #0000FF;">]</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">mat</span><span style="color: #0000FF;">[</span><span style="color: #000000;">r</span><span style="color: #0000FF;">][</span><span style="color: #000000;">c</span><span style="color: #0000FF;">]</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">for</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">for</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>
<!--</langsyntaxhighlight>-->
 
=={{header|PHP}}==
====Up to PHP version 5.6====
<langsyntaxhighlight lang="php">
function transpose($m) {
if (count($m) == 0) // special case: empty matrix
Line 3,025 ⟶ 3,384:
array_unshift($m, NULL); // the original matrix is not modified because it was passed by value
return call_user_func_array('array_map', $m);
}</langsyntaxhighlight>
 
 
====Starting with PHP 5.6====
<langsyntaxhighlight lang="php">
 
function transpose($m) {
return count($m) == 0 ? $m : (count($m) == 1 ? array_chunk($m[0], 1) : array_map(null, ...$m));
}
</syntaxhighlight>
</lang>
 
=={{header|Picat}}==
Picat has a built-in function <code>transpose/1</code> (in the <code>util</code> module).
<syntaxhighlight lang="picat">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.</syntaxhighlight>
 
{{out}}
<pre>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]</pre>
 
=={{header|PicoLisp}}==
<langsyntaxhighlight PicoLisplang="picolisp">(de matTrans (Mat)
(apply mapcar Mat list) )
 
(matTrans '((1 2 3) (4 5 6)))</langsyntaxhighlight>
{{out}}
<pre>-> ((1 4) (2 5) (3 6))</pre>
 
=={{header|PL/I}}==
<langsyntaxhighlight PLlang="pl/Ii">/* 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. */</langsyntaxhighlight>
Traditional method:
<langsyntaxhighlight PLlang="pl/Ii">/* Transpose matrix A, result at B. */
transpose: procedure (a, b);
declare (a, b) (*,*) float controlled;
Line 3,063 ⟶ 3,510:
b(*,i) = a(i,*);
end;
end transpose;</langsyntaxhighlight>
 
=={{header|Pop11}}==
<langsyntaxhighlight lang="pop11">define transpose(m) -> res;
lvars bl = boundslist(m);
if length(bl) /= 4 then
Line 3,079 ⟶ 3,526:
endfor;
endfor;
enddefine;</langsyntaxhighlight>
 
=={{header|PostScript}}==
{{libheader|initlib}}
<langsyntaxhighlight lang="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
}.</langsyntaxhighlight>
 
=={{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.
<langsyntaxhighlight lang="powerbasic">#COMPILE EXE
#DIM ALL
#COMPILER PBCC 6
Line 3,145 ⟶ 3,592:
TranspositionDemo 3, 3
TranspositionDemo 3, 7
END FUNCTION</langsyntaxhighlight>
{{out}}
<pre>initial matrix:
Line 3,170 ⟶ 3,617:
=={{header|PowerShell}}==
===Any Matrix===
<syntaxhighlight lang="powershell">
<lang PowerShell>
function transpose($a) {
$arr = @()
Line 3,229 ⟶ 3,676:
"transpose `$a ="
show (transpose $a)
</syntaxhighlight>
</lang>
<b>Output:</b>
<pre>
Line 3,276 ⟶ 3,723:
 
===Square Matrix===
<syntaxhighlight lang="powershell">
<lang PowerShell>
function transpose($a) {
if($a) {
Line 3,299 ⟶ 3,746:
""
show (transpose $a)
</syntaxhighlight>
</lang>
<b>Output:</b>
<pre>
Line 3,315 ⟶ 3,762:
In Prolog, a matrix is a list of lists. transpose/2 can be written like that.
{{works with|SWI-Prolog}}
<langsyntaxhighlight Prologlang="prolog">% transposition of a rectangular matrix
% e.g. [[1,2,3,4], [5,6,7,8]]
% give [[1,5],[2,6],[3,7],[4,8]]
Line 3,341 ⟶ 3,788:
 
% "quick" append
append_dl(X-Y, Y-Z, X-Z).</langsyntaxhighlight>
 
=={{header|PureBasic}}==
Matrices represented by integer arrays using rows as the first dimension and columns as the second dimension.
<langsyntaxhighlight PureBasiclang="purebasic">Procedure transposeMatrix(Array a(2), Array trans(2))
Protected rows, cols
Line 3,396 ⟶ 3,843:
Input()
CloseConsole()
EndIf</langsyntaxhighlight>
{{out}}
<pre>matrix m, before: (3, 4)
Line 3,410 ⟶ 3,857:
 
=={{header|Python}}==
<langsyntaxhighlight lang="python">m=((1, 1, 1, 1),
(2, 4, 8, 16),
(3, 9, 27, 81),
Line 3,417 ⟶ 3,864:
print(zip(*m))
# in Python 3.x, you would do:
# print(list(zip(*m)))</langsyntaxhighlight>
{{out}}
<pre>
Line 3,435 ⟶ 3,882:
 
Perhaps, for example, something like:
<langsyntaxhighlight lang="python"># transpose :: Matrix a -> Matrix a
def transpose(m):
if m:
Line 3,475 ⟶ 3,922:
(' of ' + type(tm[0]).__name__) if m else ''
) + ' :: ' + str(m) + ' -> ' + str(tm)
)</langsyntaxhighlight>
{{Out}}
<pre>transpose function :: (Transposition without type change):
Line 3,491 ⟶ 3,938:
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:
 
<langsyntaxhighlight lang="python"># Uneven list of lists
uls = [[10, 11], [20], [], [30, 31, 32]]
 
Line 3,498 ⟶ 3,945:
)
 
# --> []</langsyntaxhighlight>
 
At this point, short of turning to '''numpy''', we might need to write a custom function.
Line 3,505 ⟶ 3,952:
 
{{Works with|Python|3.7}}
<langsyntaxhighlight lang="python">'''Transposition of row sets with possible gaps'''
 
from collections import defaultdict
Line 3,634 ⟶ 4,081:
# MAIN ---
if __name__ == '__main__':
main()</langsyntaxhighlight>
{{Out}}
<pre>Transposition of row sets with possible gaps:
Line 3,645 ⟶ 4,092:
Not rows: [1,2,3] -> []
Nothing: [] -> []</pre>
 
=={{header|Quackery}}==
 
<syntaxhighlight lang="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</syntaxhighlight>
 
{{out}}
 
<pre>[ [ 1 2 ] [ 3 4 ] [ 5 6 ] ]
 
[ [ 1 3 5 ] [ 2 4 6 ] ]
 
[ [ 1 2 ] [ 3 4 ] [ 5 6 ] ]</pre>
 
=={{header|R}}==
<langsyntaxhighlight Rlang="r">b <- 1:5
m <- matrix(c(b, b^2, b^3, b^4), 5, 4)
print(m)
tm <- t(m)
print(tm)</langsyntaxhighlight>
 
=={{header|Racket}}==
<langsyntaxhighlight lang="racket">
#lang racket
(require math)
(matrix-transpose (matrix [[1 2] [3 4]]))
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 3,669 ⟶ 4,140:
(formerly Perl 6)
{{Works with|rakudo|2018.03}}
<syntaxhighlight lang="raku" perl6line># Transposition can be done with the reduced zip meta-operator
# on list-of-lists data structures
 
Line 3,690 ⟶ 4,161:
}
 
say @b;</langsyntaxhighlight>
 
{{output}}
Line 3,698 ⟶ 4,169:
 
=={{header|Rascal}}==
<langsyntaxhighlight Rascallang="rascal">public rel[real, real, real] matrixTranspose(rel[real x, real y, real v] matrix){
return {<y, x, v> | <x, y, v> <- matrix};
}
Line 3,707 ⟶ 4,178:
<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>
};</langsyntaxhighlight>
 
=={{header|REXX}}==
<langsyntaxhighlight 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
@.2 = 111 2222 33333 444444 5555555 66666666 777777777
Line 3,734 ⟶ 4,205:
end /*c*/
say _ /*1 line.*/
end /*r*/; return</langsyntaxhighlight>
{{out|output|text=&nbsp; when using the default input:}}
<pre>
Line 3,752 ⟶ 4,223:
 
=={{header|Ring}}==
<langsyntaxhighlight lang="ring">
load "stdlib.ring"
transpose = newlist(5,4)
Line 3,763 ⟶ 4,234:
see nl
next
</syntaxhighlight>
</lang>
Output:
<pre>
Line 3,774 ⟶ 4,245:
 
=={{header|RLaB}}==
<langsyntaxhighlight RLaBlang="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
Line 3,783 ⟶ 4,254:
0.75054022 0.464227895 0.26582235
0.226388925 0.693482786 0.11557427
0.963880314 0.203839405 0.0442493069</langsyntaxhighlight>
 
=={{header|RPL}}==
[[1 2 3 4][5 6 7 8][9 10 11 12]] TRN
{{out}}
<pre>
[[1 5 9] [2 6 10] [3 7 11] [4 8 12]]
</pre>
 
=={{header|Ruby}}==
<langsyntaxhighlight lang="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</langsyntaxhighlight>
{{out}}
<pre>
Line 3,797 ⟶ 4,275:
</pre>
or using 'matrix' from the standard library
<langsyntaxhighlight lang="ruby">require 'matrix'
 
m=Matrix[[1, 1, 1, 1],
Line 3,804 ⟶ 4,282:
[4, 16, 64, 256],
[5, 25,125, 625]]
puts m.transpose</langsyntaxhighlight>
{{out}}
<pre>
Line 3,810 ⟶ 4,288:
</pre>
or using zip:
<langsyntaxhighlight lang="ruby">def transpose(m)
m[0].zip(*m[1..-1])
end
p transpose([[1,2,3],[4,5,6]])</langsyntaxhighlight>
{{out}}
<pre>
Line 3,820 ⟶ 4,298:
 
=={{header|Run BASIC}}==
<langsyntaxhighlight 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"
Line 3,855 ⟶ 4,333:
next i
html "</table>"
end sub</langsyntaxhighlight>
{{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 />
Line 3,862 ⟶ 4,340:
=={{header|Rust}}==
===version 1===
<langsyntaxhighlight lang="rust">
struct Matrix {
dat: [[i32; 3]; 3]
Line 3,911 ⟶ 4,389:
c.print();
}
</syntaxhighlight>
</lang>
 
===version 2===
<langsyntaxhighlight lang="rust">
fn main() {
let m = vec![vec![1, 2, 3], vec![4, 5, 6]];
Line 3,940 ⟶ 4,418:
t
}
</syntaxhighlight>
</lang>
 
<b>Output:</b>
Line 3,955 ⟶ 4,433:
 
=={{header|Scala}}==
<langsyntaxhighlight 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))
 
Line 3,973 ⟶ 4,451:
1 5 9 13
2 6 10 14
3 7 11 15</langsyntaxhighlight>
 
=={{header|Scheme}}==
<langsyntaxhighlight lang="scheme">(define (transpose m)
(apply map list m))</langsyntaxhighlight>
 
=={{header|Seed7}}==
<langsyntaxhighlight lang="seed7">$ include "seed7_05.s7i";
include "float.s7i";
 
Line 4,025 ⟶ 4,503:
writeln("After Transposition:");
write(transpose(testMatrix));
end func;</langsyntaxhighlight>
 
{{out}}
Line 4,042 ⟶ 4,520:
 
=={{header|Sidef}}==
<langsyntaxhighlight lang="ruby">func transpose(matrix) {
matrix[0].range.map{|i| matrix.map{_[i]}};
};
Line 4,056 ⟶ 4,534:
transpose(m).each { |row|
"%5d" * row.len -> printlnf(row...);
}</langsyntaxhighlight>
{{out}}
<pre> 1 2 3 4 5
Line 4,067 ⟶ 4,545:
{{works with|OpenAxiom}}
{{works with|Axiom}}
<langsyntaxhighlight SPADlang="spad">(1) -> originalMatrix := matrix [[1, 1, 1, 1],[2, 4, 8, 16], _
[3, 9, 27, 81],[4, 16, 64, 256], _
[5, 25, 125, 625]]
Line 4,090 ⟶ 4,568:
| |
+1 16 81 256 625+
Type: Matrix(Integer)</langsyntaxhighlight>
 
Domain:[http://fricas.github.io/api/Matrix.html?highlight=matrix Matrix(R)]
 
=={{header|Sparkling}}==
<langsyntaxhighlight lang="sparkling">function transpose(A) {
return map(range(sizeof A), function(k, idx) {
return map(A, function(k, row) {
Line 4,101 ⟶ 4,579:
});
});
}</langsyntaxhighlight>
 
=={{header|Stata}}==
Line 4,107 ⟶ 4,585:
 
=== Stata matrices ===
<langsyntaxhighlight lang="stata">. mat a=1,2,3\4,5,6
. mat b=a'
. mat list a
Line 4,122 ⟶ 4,600:
c1 1 4
c2 2 5
c3 3 6</langsyntaxhighlight>
 
=== Mata ===
<langsyntaxhighlight lang="stata">: a=1,1i
 
: a
Line 4,145 ⟶ 4,623:
1 | 1 |
2 | 1i |
+------+</langsyntaxhighlight>
 
=={{header|Swift}}==
 
<langsyntaxhighlight lang="swift">@inlinable
public func matrixTranspose<T>(_ matrix: [[T]]) -> [[T]] {
guard !matrix.isEmpty else {
Line 4,198 ⟶ 4,676:
 
print("Output:")
printMatrix(m2)</langsyntaxhighlight>
 
{{out}}
Line 4,211 ⟶ 4,689:
 
=={{header|Tailspin}}==
<langsyntaxhighlight lang="tailspin">
templates transpose
def a: $;
Line 4,238 ⟶ 4,716:
' -> !OUT::write
$mT -> printMatrix&{w:2} -> !OUT::write
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 4,255 ⟶ 4,733:
=={{header|Tcl}}==
With core Tcl, representing a matrix as a list of lists:
<langsyntaxhighlight lang="tcl">package require Tcl 8.5
namespace path ::tcl::mathfunc
 
Line 4,298 ⟶ 4,776:
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"</langsyntaxhighlight>
{{out}}
<pre>1 1 1 1
Line 4,310 ⟶ 4,788:
1 16 81 256 625</pre>
{{tcllib|struct::matrix}}
<langsyntaxhighlight lang="tcl">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</langsyntaxhighlight>
{{out}}
<pre>1 1 1 1
Line 4,340 ⟶ 4,818:
 
A<sup>T</sup> &rarr; B
 
 
=={{header|True BASIC}}==
<syntaxhighlight lang="qbasic">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</syntaxhighlight>
 
 
=={{header|Ursala}}==
Matrices are stored as lists of lists, and transposing them is a built in operation.
<langsyntaxhighlight Ursalalang="ursala">#cast %eLL
 
example =
Line 4,350 ⟶ 4,863:
<1.,2.,3.,4.>,
<5.,6.,7.,8.>,
<9.,10.,11.,12.>></langsyntaxhighlight>
For a more verbose version, replace the ~&K7 operator with the standard library function
named transpose.
Line 4,363 ⟶ 4,876:
 
=={{header|VBA}}==
<langsyntaxhighlight lang="vb">Function transpose(m As Variant) As Variant
transpose = WorksheetFunction.transpose(m)
End Function</langsyntaxhighlight>
 
=={{header|VBScript}}==
<syntaxhighlight lang="vb">
<lang vb>
'create and display the initial matrix
WScript.StdOut.WriteLine "Initial Matrix:"
Line 4,400 ⟶ 4,913:
WScript.StdOut.WriteLine
Next
</syntaxhighlight>
</lang>
 
{{Out}}
Line 4,425 ⟶ 4,938:
{{works with|Visual Basic|5}}
{{works with|Visual Basic|6}}
<langsyntaxhighlight lang="vb">Option Explicit
'----------------------------------------------------------------------
Function TransposeMatrix(InitMatrix() As Long, TransposedMatrix() As Long)
Line 4,480 ⟶ 4,993:
TranspositionDemo 3, 3
TranspositionDemo 3, 7
End Sub</langsyntaxhighlight>
{{out}}
<pre>initial matrix:
Line 4,505 ⟶ 5,018:
=={{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.
<langsyntaxhighlight lang="wortel">@zipm [[1 2 3] [4 5 6] [7 8 9]]</langsyntaxhighlight>
Returns:
<pre>[[1 4 7] [2 5 8] [3 6 9]]</pre>
Line 4,512 ⟶ 5,025:
{{libheader|Wren-matrix}}
{{libheader|Wren-fmt}}
<langsyntaxhighlight ecmascriptlang="wren">import "./matrix" for Matrix
import "./fmt" for Fmt
 
var m = Matrix.new([
Line 4,525 ⟶ 5,038:
Fmt.mprint(m, 2, 0)
System.print("\nTransposed:\n")
Fmt.mprint(m.transpose, 2, 0)</langsyntaxhighlight>
 
{{out}}
Line 4,542 ⟶ 5,055:
| 3 6 9 12|
</pre>
 
=={{header|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.
<syntaxhighlight lang="xpl0">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);
]</syntaxhighlight>
 
{{out}}
<pre>
1 2 3 4
5 6 7 8
9 10 11 12
 
1 5 9
2 6 10
3 7 11
4 8 12
</pre>
 
=={{header|Yabasic}}==
{{trans|FreeBASIC}}
<syntaxhighlight lang="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</syntaxhighlight>
 
 
=={{header|zkl}}==
Using the GNU Scientific Library:
<langsyntaxhighlight 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
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</langsyntaxhighlight>
{{out}}
<pre>
Line 4,564 ⟶ 5,151:
Or, using lists:
{{trans|Wortel}}
<langsyntaxhighlight lang="zkl">fcn transpose(M){
if(M.len()==1) M[0].pump(List,List.create); // 1 row --> n columns
else M[0].zip(M.xplode(1));
}</langsyntaxhighlight>
The list xplode method pushes list contents on to the call stack.
<langsyntaxhighlight 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();
transpose(L(L(1,2,3))).println();
transpose(L(L(1),L(2),L(3))).println();
transpose(L(L(1))).println();</langsyntaxhighlight>
{{out}}
<pre>
Line 4,584 ⟶ 5,171:
 
=={{header|zonnon}}==
<langsyntaxhighlight lang="zonnon">
module MatrixOps;
type
Line 4,614 ⟶ 5,201:
Transposition;
end MatrixOps.
</syntaxhighlight>
</lang>
9,476

edits