Reduced row echelon form: Difference between revisions

m
m (→‎{{header|Phix}}: added syntax colouring the hard way)
 
(25 intermediate revisions by 15 users not shown)
Line 1:
 
{{wikipedia|Rref#Pseudocode}}
{{task|Matrices}}
Line 59 ⟶ 60:
{{trans|Python}}
 
<langsyntaxhighlight lang="11l">F ToReducedRowEchelonForm(&M)
V lead = 0
V rowCount = M.len
Line 90 ⟶ 91:
 
L(rw) mtx
print(rw.join(‘, ’))</langsyntaxhighlight>
 
{{out}}
Line 101 ⟶ 102:
=={{header|360 Assembly}}==
{{trans|BBC BASIC}}
<langsyntaxhighlight lang="360asm">* reduced row echelon form 27/08/2015
RREF CSECT
USING RREF,R12
Line 258 ⟶ 259:
PG DC CL48' '
YREGS
END RREF</langsyntaxhighlight>
{{out}}
<pre>
Line 271 ⟶ 272:
Therefore return this statements are returning the Matrix object itself.
 
<langsyntaxhighlight Actionscriptlang="actionscript">public function RREF():Matrix {
var lead:uint, i:uint, j:uint, r:uint = 0;
 
Line 307 ⟶ 308:
}
return this;
}</langsyntaxhighlight>
 
=={{header|Ada}}==
matrices.ads:
<langsyntaxhighlight Adalang="ada">generic
type Element_Type is private;
Zero : Element_Type;
Line 321 ⟶ 322:
array (Positive range <>, Positive range <>) of Element_Type;
function Reduced_Row_Echelon_form (Source : Matrix) return Matrix;
end Matrices;</langsyntaxhighlight>
 
matrices.adb:
<langsyntaxhighlight Adalang="ada">package body Matrices is
procedure Swap_Rows (From : in out Matrix; First, Second : in Positive) is
Temporary : Element_Type;
Line 394 ⟶ 395:
return Result;
end Reduced_Row_Echelon_form;
end Matrices;</langsyntaxhighlight>
 
Example use: main.adb:
<langsyntaxhighlight Adalang="ada">with Matrices;
with Ada.Text_IO;
procedure Main is
Line 424 ⟶ 425:
Ada.Text_IO.Put_Line ("reduced to:");
Print_Matrix (Reduced);
end Main;</langsyntaxhighlight>
 
{{out}}
Line 436 ⟶ 437:
 
=={{header|Aime}}==
<langsyntaxhighlight lang="aime">rref(list l, integer rows, columns)
{
integer e, f, i, j, lead, r;
Line 502 ⟶ 503:
 
0;
}</langsyntaxhighlight>
{{Out}}
<pre> 1 0 0 -8
Line 513 ⟶ 514:
{{works with|ALGOL 68G|Any - tested with release mk15-0.8b.fc9.i386}}
<!-- {{does not work with|ELLA ALGOL 68|Any (with appropriate job cards AND formatted transput statements removed) - tested with release 1.8.8d.fc9.i386 - ELLA has not FORMATted transput, also it generates a call to undefined C external }} -->
<langsyntaxhighlight lang="algol68">MODE FIELD = REAL; # FIELD can be REAL, LONG REAL etc, or COMPL, FRAC etc #
MODE VEC = [0]FIELD;
MODE MAT = [0,0]FIELD;
Line 566 ⟶ 567:
mat repr = $"("n(1 UPB mat-1)(f(vec repr)", "lx)f(vec repr)")"$;
 
printf((mat repr, mat, $l$))</langsyntaxhighlight>
{{out}}
<pre>
Line 576 ⟶ 577:
=={{header|ALGOL W}}==
From the pseudo code.
<langsyntaxhighlight lang="algolw">begin
% replaces M with it's reduced row echelon form %
% M should have bounds ( 0 :: rMax, 0 :: cMax ) %
Line 635 ⟶ 636:
end for_r
end
end.</langsyntaxhighlight>
{{out}}
<pre>
Line 641 ⟶ 642:
0.0 1.0 0.0 1.0
0.0 0.0 1.0 -2.0
</pre>
 
=={{header|ATS}}==
This program was made by modifying [[Gauss-Jordan_matrix_inversion#ATS]]. (The latter program is equivalent to finding the RREF of a particular matrix.)
 
<syntaxhighlight lang="ats">
%{^
#include <math.h>
#include <float.h>
%}
 
#include "share/atspre_staload.hats"
 
macdef NAN = g0f2f ($extval (float, "NAN"))
macdef Zero = g0i2f 0
macdef One = g0i2f 1
macdef Two = g0i2f 2
 
(* The following is often done by a single machine instruction. *)
macdef multiply_and_add (x, y, z) = (,(x) * ,(y)) + ,(z)
 
(*------------------------------------------------------------------*)
(* A "little matrix library" *)
 
typedef Matrix_Index_Map (m1 : int, n1 : int, m0 : int, n0 : int) =
{i1, j1 : pos | i1 <= m1; j1 <= n1}
(int i1, int j1) -<cloref0>
[i0, j0 : pos | i0 <= m0; j0 <= n0]
@(int i0, int j0)
 
datatype Real_Matrix (tk : tkind,
m1 : int, n1 : int,
m0 : int, n0 : int) =
| Real_Matrix of (matrixref (g0float tk, m0, n0),
int m1, int n1, int m0, int n0,
Matrix_Index_Map (m1, n1, m0, n0))
typedef Real_Matrix (tk : tkind, m1 : int, n1 : int) =
[m0, n0 : pos] Real_Matrix (tk, m1, n1, m0, n0)
typedef Real_Vector (tk : tkind, m1 : int, n1 : int) =
[m1 == 1 || n1 == 1] Real_Matrix (tk, m1, n1)
typedef Real_Row (tk : tkind, n1 : int) = Real_Vector (tk, 1, n1)
typedef Real_Column (tk : tkind, m1 : int) = Real_Vector (tk, m1, 1)
 
extern fn {tk : tkind}
Real_Matrix_make_elt :
{m0, n0 : pos}
(int m0, int n0, g0float tk) -< !wrt >
Real_Matrix (tk, m0, n0, m0, n0)
 
extern fn {tk : tkind}
Real_Matrix_copy :
{m1, n1 : pos}
Real_Matrix (tk, m1, n1) -< !refwrt > Real_Matrix (tk, m1, n1)
 
extern fn {tk : tkind}
Real_Matrix_copy_to :
{m1, n1 : pos}
(Real_Matrix (tk, m1, n1), (* destination *)
Real_Matrix (tk, m1, n1)) -< !refwrt >
void
 
extern fn {tk : tkind}
Real_Matrix_fill_with_elt :
{m1, n1 : pos}
(Real_Matrix (tk, m1, n1), g0float tk) -< !refwrt > void
 
extern fn {}
Real_Matrix_dimension :
{tk : tkind}
{m1, n1 : pos}
Real_Matrix (tk, m1, n1) -<> @(int m1, int n1)
 
extern fn {tk : tkind}
Real_Matrix_get_at :
{m1, n1 : pos}
{i1, j1 : pos | i1 <= m1; j1 <= n1}
(Real_Matrix (tk, m1, n1), int i1, int j1) -< !ref > g0float tk
 
extern fn {tk : tkind}
Real_Matrix_set_at :
{m1, n1 : pos}
{i1, j1 : pos | i1 <= m1; j1 <= n1}
(Real_Matrix (tk, m1, n1), int i1, int j1, g0float tk) -< !refwrt >
void
 
extern fn {}
Real_Matrix_apply_index_map :
{tk : tkind}
{m1, n1 : pos}
{m0, n0 : pos}
(Real_Matrix (tk, m0, n0), int m1, int n1,
Matrix_Index_Map (m1, n1, m0, n0)) -<>
Real_Matrix (tk, m1, n1)
 
extern fn {}
Real_Matrix_transpose :
(* This is transposed INDEXING. It does NOT copy the data. *)
{tk : tkind}
{m1, n1 : pos}
{m0, n0 : pos}
Real_Matrix (tk, m1, n1, m0, n0) -<>
Real_Matrix (tk, n1, m1, m0, n0)
 
extern fn {}
Real_Matrix_block :
(* This is block (submatrix) INDEXING. It does NOT copy the data. *)
{tk : tkind}
{p0, p1 : pos | p0 <= p1}
{q0, q1 : pos | q0 <= q1}
{m1, n1 : pos | p1 <= m1; q1 <= n1}
{m0, n0 : pos}
(Real_Matrix (tk, m1, n1, m0, n0),
int p0, int p1, int q0, int q1) -<>
Real_Matrix (tk, p1 - p0 + 1, q1 - q0 + 1, m0, n0)
 
extern fn {tk : tkind}
Real_Matrix_unit_matrix :
{m : pos}
int m -< !refwrt > Real_Matrix (tk, m, m)
 
extern fn {tk : tkind}
Real_Matrix_unit_matrix_to :
{m : pos}
Real_Matrix (tk, m, m) -< !refwrt > void
 
extern fn {tk : tkind}
Real_Matrix_matrix_sum :
{m, n : pos}
(Real_Matrix (tk, m, n), Real_Matrix (tk, m, n)) -< !refwrt >
Real_Matrix (tk, m, n)
 
extern fn {tk : tkind}
Real_Matrix_matrix_sum_to :
{m, n : pos}
(Real_Matrix (tk, m, n), (* destination*)
Real_Matrix (tk, m, n),
Real_Matrix (tk, m, n)) -< !refwrt >
void
 
extern fn {tk : tkind}
Real_Matrix_matrix_difference :
{m, n : pos}
(Real_Matrix (tk, m, n), Real_Matrix (tk, m, n)) -< !refwrt >
Real_Matrix (tk, m, n)
 
extern fn {tk : tkind}
Real_Matrix_matrix_difference_to :
{m, n : pos}
(Real_Matrix (tk, m, n), (* destination*)
Real_Matrix (tk, m, n),
Real_Matrix (tk, m, n)) -< !refwrt >
void
 
extern fn {tk : tkind}
Real_Matrix_matrix_product :
{m, n, p : pos}
(Real_Matrix (tk, m, n), Real_Matrix (tk, n, p)) -< !refwrt >
Real_Matrix (tk, m, p)
 
extern fn {tk : tkind}
Real_Matrix_matrix_product_to :
{m, n, p : pos}
(Real_Matrix (tk, m, p), (* destination*)
Real_Matrix (tk, m, n),
Real_Matrix (tk, n, p)) -< !refwrt >
void
 
extern fn {tk : tkind}
Real_Matrix_scalar_product :
{m, n : pos}
(Real_Matrix (tk, m, n), g0float tk) -< !refwrt >
Real_Matrix (tk, m, n)
 
extern fn {tk : tkind}
Real_Matrix_scalar_product_2 :
{m, n : pos}
(g0float tk, Real_Matrix (tk, m, n)) -< !refwrt >
Real_Matrix (tk, m, n)
 
extern fn {tk : tkind}
Real_Matrix_scalar_product_to :
{m, n : pos}
(Real_Matrix (tk, m, n), (* destination*)
Real_Matrix (tk, m, n), g0float tk) -< !refwrt > void
 
extern fn {tk : tkind} (* Useful for debugging. *)
Real_Matrix_fprint :
{m, n : pos}
(FILEref, Real_Matrix (tk, m, n)) -<1> void
 
overload copy with Real_Matrix_copy
overload copy_to with Real_Matrix_copy_to
overload fill_with_elt with Real_Matrix_fill_with_elt
overload dimension with Real_Matrix_dimension
overload [] with Real_Matrix_get_at
overload [] with Real_Matrix_set_at
overload apply_index_map with Real_Matrix_apply_index_map
overload transpose with Real_Matrix_transpose
overload block with Real_Matrix_block
overload unit_matrix with Real_Matrix_unit_matrix
overload unit_matrix_to with Real_Matrix_unit_matrix_to
overload matrix_sum with Real_Matrix_matrix_sum
overload matrix_sum_to with Real_Matrix_matrix_sum_to
overload matrix_difference with Real_Matrix_matrix_difference
overload matrix_difference_to with Real_Matrix_matrix_difference_to
overload matrix_product with Real_Matrix_matrix_product
overload matrix_product_to with Real_Matrix_matrix_product_to
overload scalar_product with Real_Matrix_scalar_product
overload scalar_product with Real_Matrix_scalar_product_2
overload scalar_product_to with Real_Matrix_scalar_product_to
overload + with matrix_sum
overload - with matrix_difference
overload * with matrix_product
overload * with scalar_product
 
(*------------------------------------------------------------------*)
(* Implementation of the "little matrix library" *)
 
implement {tk}
Real_Matrix_make_elt (m0, n0, elt) =
Real_Matrix (matrixref_make_elt<g0float tk> (i2sz m0, i2sz n0, elt),
m0, n0, m0, n0, lam (i1, j1) => @(i1, j1))
 
implement {}
Real_Matrix_dimension A =
case+ A of Real_Matrix (_, m1, n1, _, _, _) => @(m1, n1)
 
implement {tk}
Real_Matrix_get_at (A, i1, j1) =
let
val+ Real_Matrix (storage, _, _, _, n0, index_map) = A
val @(i0, j0) = index_map (i1, j1)
in
matrixref_get_at<g0float tk> (storage, pred i0, n0, pred j0)
end
 
implement {tk}
Real_Matrix_set_at (A, i1, j1, x) =
let
val+ Real_Matrix (storage, _, _, _, n0, index_map) = A
val @(i0, j0) = index_map (i1, j1)
in
matrixref_set_at<g0float tk> (storage, pred i0, n0, pred j0, x)
end
 
implement {}
Real_Matrix_apply_index_map (A, m1, n1, index_map) =
(* This is not the most efficient way to acquire new indexing, but
it will work. It requires three closures, instead of the two
needed by our implementations of "transpose" and "block". *)
let
val+ Real_Matrix (storage, m1a, n1a, m0, n0, index_map_1a) = A
in
Real_Matrix (storage, m1, n1, m0, n0,
lam (i1, j1) =>
index_map_1a (i1a, j1a) where
{ val @(i1a, j1a) = index_map (i1, j1) })
end
 
implement {}
Real_Matrix_transpose A =
let
val+ Real_Matrix (storage, m1, n1, m0, n0, index_map) = A
in
Real_Matrix (storage, n1, m1, m0, n0,
lam (i1, j1) => index_map (j1, i1))
end
 
implement {}
Real_Matrix_block (A, p0, p1, q0, q1) =
let
val+ Real_Matrix (storage, m1, n1, m0, n0, index_map) = A
in
Real_Matrix (storage, succ (p1 - p0), succ (q1 - q0), m0, n0,
lam (i1, j1) =>
index_map (p0 + pred i1, q0 + pred j1))
end
 
implement {tk}
Real_Matrix_copy A =
let
val @(m1, n1) = dimension A
val C = Real_Matrix_make_elt<tk> (m1, n1, A[1, 1])
val () = copy_to<tk> (C, A)
in
C
end
 
implement {tk}
Real_Matrix_copy_to (Dst, Src) =
let
val @(m1, n1) = dimension Src
prval [m1 : int] EQINT () = eqint_make_gint m1
prval [n1 : int] EQINT () = eqint_make_gint n1
 
var i : intGte 1
in
for* {i : pos | i <= m1 + 1} .<(m1 + 1) - i>.
(i : int i) =>
(i := 1; i <> succ m1; i := succ i)
let
var j : intGte 1
in
for* {j : pos | j <= n1 + 1} .<(n1 + 1) - j>.
(j : int j) =>
(j := 1; j <> succ n1; j := succ j)
Dst[i, j] := Src[i, j]
end
end
 
implement {tk}
Real_Matrix_fill_with_elt (A, elt) =
let
val @(m1, n1) = dimension A
prval [m1 : int] EQINT () = eqint_make_gint m1
prval [n1 : int] EQINT () = eqint_make_gint n1
 
var i : intGte 1
in
for* {i : pos | i <= m1 + 1} .<(m1 + 1) - i>.
(i : int i) =>
(i := 1; i <> succ m1; i := succ i)
let
var j : intGte 1
in
for* {j : pos | j <= n1 + 1} .<(n1 + 1) - j>.
(j : int j) =>
(j := 1; j <> succ n1; j := succ j)
A[i, j] := elt
end
end
 
implement {tk}
Real_Matrix_unit_matrix {m} m =
let
val A = Real_Matrix_make_elt<tk> (m, m, Zero)
var i : intGte 1
in
for* {i : pos | i <= m + 1} .<(m + 1) - i>.
(i : int i) =>
(i := 1; i <> succ m; i := succ i)
A[i, i] := One;
A
end
 
implement {tk}
Real_Matrix_unit_matrix_to A =
let
val @(m, _) = dimension A
prval [m : int] EQINT () = eqint_make_gint m
 
var i : intGte 1
in
for* {i : pos | i <= m + 1} .<(m + 1) - i>.
(i : int i) =>
(i := 1; i <> succ m; i := succ i)
let
var j : intGte 1
in
for* {j : pos | j <= m + 1} .<(m + 1) - j>.
(j : int j) =>
(j := 1; j <> succ m; j := succ j)
A[i, j] := (if i = j then One else Zero)
end
end
 
implement {tk}
Real_Matrix_matrix_sum (A, B) =
let
val @(m, n) = dimension A
val C = Real_Matrix_make_elt<tk> (m, n, NAN)
val () = matrix_sum_to<tk> (C, A, B)
in
C
end
 
implement {tk}
Real_Matrix_matrix_sum_to (C, A, B) =
let
val @(m, n) = dimension A
prval [m : int] EQINT () = eqint_make_gint m
prval [n : int] EQINT () = eqint_make_gint n
 
var i : intGte 1
in
for* {i : pos | i <= m + 1} .<(m + 1) - i>.
(i : int i) =>
(i := 1; i <> succ m; i := succ i)
let
var j : intGte 1
in
for* {j : pos | j <= n + 1} .<(n + 1) - j>.
(j : int j) =>
(j := 1; j <> succ n; j := succ j)
C[i, j] := A[i, j] + B[i, j]
end
end
 
implement {tk}
Real_Matrix_matrix_difference (A, B) =
let
val @(m, n) = dimension A
val C = Real_Matrix_make_elt<tk> (m, n, NAN)
val () = matrix_difference_to<tk> (C, A, B)
in
C
end
 
implement {tk}
Real_Matrix_matrix_difference_to (C, A, B) =
let
val @(m, n) = dimension A
prval [m : int] EQINT () = eqint_make_gint m
prval [n : int] EQINT () = eqint_make_gint n
 
var i : intGte 1
in
for* {i : pos | i <= m + 1} .<(m + 1) - i>.
(i : int i) =>
(i := 1; i <> succ m; i := succ i)
let
var j : intGte 1
in
for* {j : pos | j <= n + 1} .<(n + 1) - j>.
(j : int j) =>
(j := 1; j <> succ n; j := succ j)
C[i, j] := A[i, j] - B[i, j]
end
end
 
implement {tk}
Real_Matrix_matrix_product (A, B) =
let
val @(m, n) = dimension A and @(_, p) = dimension B
val C = Real_Matrix_make_elt<tk> (m, p, NAN)
val () = matrix_product_to<tk> (C, A, B)
in
C
end
 
implement {tk}
Real_Matrix_matrix_product_to (C, A, B) =
let
val @(m, n) = dimension A and @(_, p) = dimension B
prval [m : int] EQINT () = eqint_make_gint m
prval [n : int] EQINT () = eqint_make_gint n
prval [p : int] EQINT () = eqint_make_gint p
 
var i : intGte 1
in
for* {i : pos | i <= m + 1} .<(m + 1) - i>.
(i : int i) =>
(i := 1; i <> succ m; i := succ i)
let
var k : intGte 1
in
for* {k : pos | k <= p + 1} .<(p + 1) - k>.
(k : int k) =>
(k := 1; k <> succ p; k := succ k)
let
var j : intGte 1
in
C[i, k] := A[i, 1] * B[1, k];
for* {j : pos | j <= n + 1} .<(n + 1) - j>.
(j : int j) =>
(j := 2; j <> succ n; j := succ j)
C[i, k] :=
multiply_and_add (A[i, j], B[j, k], C[i, k])
end
end
end
 
implement {tk}
Real_Matrix_scalar_product (A, r) =
let
val @(m, n) = dimension A
val C = Real_Matrix_make_elt<tk> (m, n, NAN)
val () = scalar_product_to<tk> (C, A, r)
in
C
end
 
implement {tk}
Real_Matrix_scalar_product_2 (r, A) =
Real_Matrix_scalar_product<tk> (A, r)
 
implement {tk}
Real_Matrix_scalar_product_to (C, A, r) =
let
val @(m, n) = dimension A
prval [m : int] EQINT () = eqint_make_gint m
prval [n : int] EQINT () = eqint_make_gint n
 
var i : intGte 1
in
for* {i : pos | i <= m + 1} .<(m + 1) - i>.
(i : int i) =>
(i := 1; i <> succ m; i := succ i)
let
var j : intGte 1
in
for* {j : pos | j <= n + 1} .<(n + 1) - j>.
(j : int j) =>
(j := 1; j <> succ n; j := succ j)
C[i, j] := A[i, j] * r
end
end
 
implement {tk}
Real_Matrix_fprint {m, n} (outf, A) =
let
val @(m, n) = dimension A
var i : intGte 1
in
for* {i : pos | i <= m + 1} .<(m + 1) - i>.
(i : int i) =>
(i := 1; i <> succ m; i := succ i)
let
var j : intGte 1
in
for* {j : pos | j <= n + 1} .<(n + 1) - j>.
(j : int j) =>
(j := 1; j <> succ n; j := succ j)
let
typedef FILEstar = $extype"FILE *"
extern castfn FILEref2star : FILEref -<> FILEstar
val _ = $extfcall (int, "fprintf", FILEref2star outf,
"%16.6g", A[i, j])
in
end;
fprintln! (outf)
end
end
 
(*------------------------------------------------------------------*)
(* Reduced row echelon form, by Gauss-Jordan elimination *)
 
extern fn {tk : tkind}
Real_Matrix_reduced_row_echelon_form :
{m, n : pos}
Real_Matrix (tk, m, n) -< !refwrt > Real_Matrix (tk, m, n)
 
implement {tk}
Real_Matrix_reduced_row_echelon_form {m, n} A =
let
val @(m, n) = dimension A
typedef one_to_m = intBtwe (1, m)
typedef one_to_n = intBtwe (1, n)
 
(* Partial pivoting, to improve the numerical stability. *)
implement
array_tabulate$fopr<one_to_m> i =
let
val i = g1ofg0 (sz2i (succ i))
val () = assertloc ((1 <= i) * (i <= m))
in
i
end
val rows_permutation =
$effmask_all arrayref_tabulate<one_to_m> (i2sz m)
fn
index_map : Matrix_Index_Map (m, n, m, n) =
lam (i1, j1) => $effmask_ref
(@(i0, j1) where { val i0 = rows_permutation[i1 - 1] })
 
val A = apply_index_map (copy<tk> A, m, n, index_map)
 
fn {}
exchange_rows (i1 : one_to_m,
i2 : one_to_m) :<!refwrt> void =
if i1 <> i2 then
let
val k1 = rows_permutation[pred i1]
and k2 = rows_permutation[pred i2]
in
rows_permutation[pred i1] := k2;
rows_permutation[pred i2] := k1
end
 
fn {}
normalize_pivot_row (i : one_to_m,
j : one_to_n) :<!refwrt> void =
let
prval [j : int] EQINT () = eqint_make_gint j
val pivot_val = A[i, j]
var k : intGte 1
in
A[i, j] := One;
for* {k : int | j + 1 <= k; k <= n + 1} .<(n + 1) - k>.
(k : int k) =>
(k := succ j; k <> succ n; k := succ k)
A[i, k] := A[i, k] / pivot_val
end
 
fn
subtract_normalized_pivot_row (ipiv : one_to_m,
i : one_to_m,
j : one_to_n) :<!refwrt> void =
let
prval [j : int] EQINT () = eqint_make_gint j
val factor = ~A[i, j]
var k : intGte 1
in
A[i, j] := Zero;
for* {k : int | j + 1 <= k; k <= n + 1} .<(n + 1) - k>.
(k : int k) =>
(k := succ j; k <> succ n; k := succ k)
A[i, k] := multiply_and_add (A[ipiv, k], factor, A[i, k])
end
 
fun
main_loop {i, j : pos | i <= m; i <= j; j <= n + 1}
.<(n + 1) - j>.
(i : int i, j : int j) :<!refwrt> void =
if j <> succ n then
let
fun
select_pivot {k : int | i <= k; k <= m + 1}
.<(m + 1) - k>.
(k : int k,
max_abs : g0float tk,
k_max_abs : intBtwe (i - 1, m))
:<!ref> intBtwe (i - 1, m) =
if k = succ m then
k_max_abs
else
let
val abs_akj = abs A[k, j]
in
if abs_akj > max_abs then
select_pivot (succ k, abs_akj, k)
else
select_pivot (succ k, max_abs, k_max_abs)
end
 
val i_pivot = select_pivot (i, Zero, pred i)
prval [i_pivot : int] EQINT () = eqint_make_gint i_pivot
in
if i_pivot = pred i then
(* There is no pivot in this column. *)
main_loop (i, succ j)
else
let
var k : intGte 1
in
exchange_rows (i_pivot, i);
normalize_pivot_row (i, j);
for* {k : int | 1 <= k; k <= i} .<i - k>.
(k : int k) =>
(k := 1; k <> i; k := succ k)
subtract_normalized_pivot_row (i, k, j);
for* {k : int | i + 1 <= k; k <= m + 1} .<(m + 1) - k>.
(k : int k) =>
(k := succ i; k <> succ m; k := succ k)
subtract_normalized_pivot_row (i, k, j);
if i <> m then
main_loop (succ i, succ j)
end
end
in
main_loop (1, 1);
A
end
 
overload reduced_row_echelon_form with
Real_Matrix_reduced_row_echelon_form
 
(*------------------------------------------------------------------*)
 
implement
main0 () =
let
val () = println! ()
val () = println! ("Here is the requested solution:")
val () = println! ()
val A = Real_Matrix_make_elt (3, 4, NAN)
val () =
(A[1,1] := 1.0; A[1,2] := 2.0; A[1,3] := ~1.0; A[1,4] := ~4.0;
A[2,1] := 2.0; A[2,2] := 3.0; A[2,3] := ~1.0; A[2,4] := ~11.0;
A[3,1] := ~2.0; A[3,2] := 0.0; A[3,3] := ~3.0; A[3,4] := 22.0)
val B = reduced_row_echelon_form A
val () = Real_Matrix_fprint (stdout_ref, B)
 
val () = println! ()
val () = println! ("Here is a RREF with a more interesting shape:")
val () = println! ()
val A = Real_Matrix_make_elt (3, 5, NAN)
val () =
(A[1,1] := 0.0; A[1,2] := 0.0; A[1,3] := ~1.0; A[1,4] := 2.0; A[1,5] := 0.0;
A[2,1] := 0.0; A[2,2] := 0.0; A[2,3] := ~1.0; A[2,4] := 1.0; A[2,5] := 1.0;
A[3,1] := 2.0; A[3,2] := 8.0; A[3,3] := 1.0; A[3,4] := ~4.0; A[3,5] := 2.0)
val B = reduced_row_echelon_form A
val () = Real_Matrix_fprint (stdout_ref, B)
 
val () = println! ()
val () = println! ("It is the RREF of this matrix:")
val () = println! ()
val () = Real_Matrix_fprint (stdout_ref, A)
 
val () = println! ()
in
end
 
(*------------------------------------------------------------------*)
</syntaxhighlight>
 
{{out}}
<pre>$ patscc -std=gnu2x -g -O2 -DATS_MEMALLOC_GCBDW reduced_row_echelon_task.dats -lgc && ./a.out
 
Here is the requested solution:
 
1 0 0 -8
0 1 0 1
0 0 1 -2
 
Here is a RREF with a more interesting shape:
 
1 4 0 0 0
0 0 1 0 -2
0 0 0 1 -1
 
It is the RREF of this matrix:
 
0 0 -1 2 0
0 0 -1 1 1
2 8 1 -4 2
 
</pre>
 
=={{header|AutoHotkey}}==
<langsyntaxhighlight AutoHotkeylang="autohotkey">ToReducedRowEchelonForm(M){
rowCount := M.Count() ; the number of rows in M
columnCount := M.1.Count() ; the number of columns in M
Line 680 ⟶ 1,408:
}
return M
}</langsyntaxhighlight>
Examples:<langsyntaxhighlight AutoHotkeylang="autohotkey">M := [[1 , 2, -1, -4 ]
, [2 , 3, -1, -11]
, [-2, 0, -3, 22]]
Line 693 ⟶ 1,421:
}
MsgBox % output
return</langsyntaxhighlight>
{{out}}
<pre>1 0 0 -8
Line 701 ⟶ 1,429:
 
=={{header|AutoIt}}==
<syntaxhighlight lang="autoit">
<lang AutoIt>
Global $ivMatrix[3][4] = [[1, 2, -1, -4],[2, 3, -1, -11],[-2, 0, -3, 22]]
ToReducedRowEchelonForm($ivMatrix)
Line 754 ⟶ 1,482:
Return $matrix
EndFunc ;==>ToReducedRowEchelonForm
</syntaxhighlight>
</lang>
{{out}}
<pre>[1,0,0,-8]
Line 760 ⟶ 1,488:
[-0,-0,1,-2]</pre>
 
=={{header|BBC BASIC}}==
==={{header|BASIC256}}===
<syntaxhighlight lang="basic256">arraybase 1
global matrix
dim matrix = {{1, 2, -1, -4}, {2, 3, -1, -11}, { -2, 0, -3, 22}}
 
call RREF (matrix)
 
for row = 1 to 3
for col = 1 to 4
if matrix[row, col] = 0 then
print "0"; chr(9);
else
print matrix[row, col]; chr(9);
end if
next
print
next
end
 
subroutine RREF(m)
nrows = matrix[?,]
ncols = matrix[,?]
lead = 1
for r = 1 to nrows
if lead >= ncols then exit for
i = r
while matrix[i, lead] = 0
i += 1
if i = nrows then
i = r
lead += 1
if lead = ncols then exit for
end if
end while
for j = 1 to ncols
temp = matrix[i, j]
matrix[i, j] = matrix[r, j]
matrix[r, j] = temp
next
n = matrix[r, lead]
if n <> 1 then
for j = 0 to ncols
matrix[r, j] /= n
next
end if
for i = 1 to nrows
if i <> r then
n = matrix[i, lead]
for j = 1 to ncols
matrix[i, j] -= matrix[r, j] * n
next
end if
next
lead += 1
next
end subroutine</syntaxhighlight>
 
==={{header|BBC BASIC}}===
{{works with|BBC BASIC for Windows}}
<langsyntaxhighlight lang="bbcbasic"> DIM matrix(2,3)
matrix() = 1, 2, -1, -4, \
\ 2, 3, -1, -11, \
Line 803 ⟶ 1,589:
lead% += 1
NEXT r%
ENDPROC</langsyntaxhighlight>
{{out}}
<pre>
Line 812 ⟶ 1,598:
 
=={{header|C}}==
<langsyntaxhighlight lang="c">#include <stdio.h>
#define TALLOC(n,typ) malloc(n*sizeof(typ))
 
Line 967 ⟶ 1,753:
MtxDisplay(m1);
return 0;
}</langsyntaxhighlight>
 
=={{header|C sharp|C#}}==
<langsyntaxhighlight lang="csharp">using System;
 
namespace rref
Line 1,029 ⟶ 1,815:
}
}
}</langsyntaxhighlight>
 
=={{header|C++}}==
Line 1,037 ⟶ 1,823:
 
{{works with|g++|4.1.2 20061115 (prerelease) (Debian 4.1.1-21)}}
<langsyntaxhighlight lang="cpp">#include <algorithm> // for std::swap
#include <cstddef>
#include <cassert>
Line 1,222 ⟶ 2,008:
 
return EXIT_SUCCESS;
}</langsyntaxhighlight>
{{out}}
<pre>
Line 1,232 ⟶ 2,018:
=={{header|Common Lisp}}==
Direct implementation of the pseudo-code given.
<langsyntaxhighlight lang="lisp">(defun convert-to-row-echelon-form (matrix)
(let* ((dimensions (array-dimensions matrix))
(row-count (first dimensions))
Line 1,275 ⟶ 2,061:
(* scale (aref matrix r c))))))
(incf lead))
:finally (return matrix)))))</langsyntaxhighlight>
 
=={{header|D}}==
<langsyntaxhighlight lang="d">import std.stdio, std.algorithm, std.array, std.conv;
 
void toReducedRowEchelonForm(T)(T[][] M) pure nothrow @nogc {
Line 1,319 ⟶ 2,105:
A.toReducedRowEchelonForm;
writefln("%(%(%2d %)\n%)", A);
}</langsyntaxhighlight>
{{out}}
<pre> 1 0 0 -8
0 1 0 1
0 0 1 -2</pre>
 
=={{header|EasyLang}}==
{{trans|Go}}
<syntaxhighlight>
proc rref . m[][] .
nrow = len m[][]
ncol = len m[1][]
lead = 1
for r to nrow
if lead > ncol
return
.
i = r
while m[i][lead] = 0
i += 1
if i > nrow
i = r
lead += 1
if lead > ncol
return
.
.
.
swap m[i][] m[r][]
m = m[r][lead]
for k to ncol
m[r][k] /= m
.
for i to nrow
if i <> r
m = m[i][lead]
for k to ncol
m[i][k] -= m * m[r][k]
.
.
.
lead += 1
.
.
test[][] = [ [ 1 2 -1 -4 ] [ 2 3 -1 -11 ] [ -2 0 -3 22 ] ]
rref test[][]
print test[][]
</syntaxhighlight>
 
=={{header|Euphoria}}==
<langsyntaxhighlight lang="euphoria">function ToReducedRowEchelonForm(sequence M)
integer lead,rowCount,columnCount,i
sequence temp
Line 1,364 ⟶ 2,193:
{ { 1, 2, -1, -4 },
{ 2, 3, -1, -11 },
{ -2, 0, -3, 22 } })</langsyntaxhighlight>
 
{{out}}
Line 1,374 ⟶ 2,203:
 
=={{header|Factor}}==
<langsyntaxhighlight lang="factor">USE: math.matrices.elimination
{ { 1 2 -1 -4 } { 2 3 -1 -11 } { -2 0 -3 22 } } solution .</langsyntaxhighlight>
{{out}}
<pre>
Line 1,382 ⟶ 2,211:
 
=={{header|Fortran}}==
<langsyntaxhighlight lang="fortran">module Rref
implicit none
contains
Line 1,420 ⟶ 2,249:
deallocate(trow)
end subroutine to_rref
end module Rref</langsyntaxhighlight>
 
<langsyntaxhighlight lang="fortran">program prg_test
use rref
implicit none
Line 1,444 ⟶ 2,273:
end do
 
end program prg_test</langsyntaxhighlight>
 
=={{header|FreeBASIC}}==
Include the code from [[Matrix multiplication#FreeBASIC]] because this function uses the matrix type defined there and I don't want to reproduce it all here.
 
<langsyntaxhighlight lang="freebasic">#include once "matmult.bas"
 
sub rowswap( byval M as Matrix, i as uinteger, j as uinteger )
Line 1,509 ⟶ 2,338:
next j
print
next i</langsyntaxhighlight>
{{out}}
<pre>
Line 1,520 ⟶ 2,349:
===2D representation===
From WP pseudocode:
<langsyntaxhighlight lang="go">package main
 
import "fmt"
Line 1,578 ⟶ 2,407:
lead++
}
}</langsyntaxhighlight>
{{out}} (not so pretty, sorry)
<pre>
Line 1,591 ⟶ 2,420:
 
===Flat representation===
<langsyntaxhighlight lang="go">package main
 
import "fmt"
Line 1,673 ⟶ 2,502:
m.rref()
m.print("Reduced:")
}</langsyntaxhighlight>
{{out}}
<pre>
Line 1,692 ⟶ 2,521:
Options are provided for both ''partial pivoting'' and ''scaled partial pivoting''.
The default option is no pivoting at all.
<langsyntaxhighlight lang="groovy">enum Pivoting {
NONE({ i, it -> 1 }),
PARTIAL({ i, it -> - (it[i].abs()) }),
Line 1,723 ⟶ 2,552:
}
matrix
}</langsyntaxhighlight>
 
This test first demonstrates the test case provided, and then demonstrates another test case designed to show the dangers of not using pivoting on an otherwise solvable matrix. Both test cases exercise all three pivoting options.
<langsyntaxhighlight lang="groovy">def matrixCopy = { matrix -> matrix.collect { row -> row.collect { it } } }
 
println "Tests for matrix A:"
Line 1,771 ⟶ 2,600:
println "pivoting == Pivoting.SCALED"
reducedRowEchelonForm(matrixCopy(b), Pivoting.SCALED).each { println it }
println()</langsyntaxhighlight>
 
{{out}}
Line 1,815 ⟶ 2,644:
This program was produced by translating from the Python and gradually refactoring the result into a more functional style.
 
<langsyntaxhighlight lang="haskell">import Data.List (find)
 
rref :: Fractional a => [[a]] -> [[a]]
Line 1,846 ⟶ 2,675:
{- Replaces the element at the given index. -}
replace n e l = a ++ e : b
where (a, _ : b) = splitAt n l</langsyntaxhighlight>
 
=={{header|Icon}} and {{header|Unicon}}==
 
Works in both languages:
<langsyntaxhighlight lang="unicon">procedure main(A)
tM := [[ 1, 2, -1, -4],
[ 2, 3, -1,-11],
Line 1,883 ⟶ 2,712:
procedure showMat(M)
every r := !M do every writes(right(!r,5)||" " | "\n")
end</langsyntaxhighlight>
 
{{out}}
Line 1,895 ⟶ 2,724:
 
=={{header|J}}==
The reduced row echelon form of a matrix can be obtained using the <code>gauss_jordan</code> verb from the [httphttps://www.jsoftwaregithub.com/wsvnjsoftware/addonsmath_misc/trunkblob/math/miscmaster/linear.ijs linear.ijs script], available as part of the <code>math/misc</code> addon. <code>gauss_jordan</code> and the verb <code>pivot</code> are shown below (in a mediawiki "[Expand]" region) for completeness:
 
'''SolutionImplementation:'''
<langsyntaxhighlight lang="j" class="mw-collapsible mw-collapsed">NB.*pivot v Pivot at row, column
NB. form: (row,col) pivot M
pivot=: dyad define
Line 1,933 ⟶ 2,762:
end.
mtx
)</langsyntaxhighlight>
 
<hr style="clear: both"/>
'''Usage:'''
<langsyntaxhighlight lang="j"> require 'math/misc/linear'
]A=: 1 2 _1 _4 , 2 3 _1 _11 ,: _2 0 _3 22
1 2 _1 _4
Line 1,945 ⟶ 2,775:
1 0 0 _8
0 1 0 1
0 0 1 _2</langsyntaxhighlight>
 
Additional examples, recommended on talk page:
 
<syntaxhighlight lang="j">
<lang j>
gauss_jordan 2 0 _1 0 0,1 0 0 _1 0,3 0 0 _2 _1,0 1 0 0 _2,:0 1 _1 0 0
1 0 0 0 _1
Line 1,965 ⟶ 2,795:
1 0
0 1
0 0</langsyntaxhighlight>
 
And:
 
<langsyntaxhighlight lang="j">mat=: 0 ". ];._2 noun define
1 0 0 0 0 0 1 0 0 0 0 _1 0 0 0 0 0 0
1 0 0 0 0 0 0 1 0 0 0 0 _1 0 0 0 0 0
Line 2,005 ⟶ 2,835:
0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0.512821
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 1
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0.820513</langsyntaxhighlight>
 
=={{header|Java}}==
''This requires Apache Commons 2.2+''
<langsyntaxhighlight lang="java">import java.util.*;
import java.lang.Math;
import org.apache.commons.math.fraction.Fraction;
Line 2,268 ⟶ 3,098:
System.out.println("after\n" + a.toString() + "\n");
}
}</langsyntaxhighlight>
 
=={{header|JavaScript}}==
{{works with|SpiderMonkey}} for the <code>print()</code> function.
Extends the Matrix class defined at [[Matrix Transpose#JavaScript]]
<langsyntaxhighlight lang="javascript">// modifies the matrix in-place
Matrix.prototype.toReducedRowEchelonForm = function() {
var lead = 0;
Line 2,326 ⟶ 3,156:
[ 3, 3, 0, 7]
]);
print(m.toReducedRowEchelonForm());</langsyntaxhighlight>
{{out}}
<pre>1,0,0,-8
Line 2,335 ⟶ 3,165:
0,1,0,1.666666666666667
0,0,1,1</pre>
 
=={{header|jq}}==
{{works with|jq}}
'''Also works with gojq, the Go implementation of jq, and with fq.'''
 
'''Generic Functions'''
<syntaxhighlight lang=jq>
# swap .[$i] and .[$j]
def array_swap($i; $j):
if $i == $j then .
elif $i < $j then array_swap($j; $i)
else .[$i] as $t | .[:$j] + [$t] + .[$j:$i] + .[$i + 1:]
end ;
 
# element-wise subtraction: $a - $b
def array_subtract($a; $b):
$a | [range(0;length) as $i | .[$i] - $b[$i]];
 
def lpad($len):
tostring | ($len - length) as $l | (" " * $l)[:$l] + .;
 
# Ensure -0 prints as 0
def matrix_print:
([.[][] | tostring | length] | max) as $max
| .[] | map(if . == 0 then 0 else . end | lpad($max))
| join(" ");
</syntaxhighlight>
'''The Task'''
<syntaxhighlight lang=jq>
# RREF
# assume input is a rectangular numeric matrix
def toReducedRowEchelonForm:
length as $nr
| (.[0]|length) as $nc
| { lead: 0, r: -1, a: .}
| until ($nc == .lead or .r == $nr;
.r += 1
| .r as $r
| .i = $r
| until ($nc == .lead or .a[.i][.lead] != 0;
.i += 1
| if $nr == .i
then .i = $r
| .lead += 1
else .
end )
| if $nc > .lead and $nr > $r
then .i as $i
| .a |= array_swap($i; $r)
| .a[$r][.lead] as $div
| if $div != 0
then .a[$r] |= map(. / $div)
else .
end
| reduce range(0; $nr) as $k (.;
if $k != $r
then .a[$k][.lead] as $mult
| .a[$k] = array_subtract(.a[$k]; (.a[$r] | map(. * $mult)))
else .
end )
| .lead += 1
else .
end )
| .a;
 
[ [ 1, 2, -1, -4],
[ 2, 3, -1, -11],
[-2, 0, -3, 22] ],
[ [1, 2, -1, -4],
[2, 4, -1, -11],
[-2, 0, -6, 24] ]
| "Original:", matrix_print, "",
"RREF:", (toReducedRowEchelonForm|matrix_print), "\n"
</syntaxhighlight>
{{output}}
'''Invocation:''' jq -nrc -f reduced-row-echelon-form.jq
<pre>
Original:
1 2 -1 -4
2 3 -1 -11
-2 0 -3 22
 
RREF:
1 0 0 -8
0 1 0 1
0 0 1 -2
 
 
Original:
1 2 -1 -4
2 4 -1 -11
-2 0 -6 24
 
RREF:
1 0 0 -3
0 1 0 -2
0 0 1 -3
</pre>
 
=={{header|Julia}}==
Line 2,354 ⟶ 3,283:
 
=={{header|Kotlin}}==
<langsyntaxhighlight lang="scala">// version 1.1.51
 
typealias Matrix = Array<DoubleArray>
Line 2,433 ⟶ 3,362:
m.printf("Reduced row echelon form:")
}
}</langsyntaxhighlight>
 
{{out}}
Line 2,463 ⟶ 3,392:
 
=={{header|Lua}}==
<langsyntaxhighlight lang="lua">function ToReducedRowEchelonForm ( M )
local lead = 1
local n_rows, n_cols = #M, #M[1]
Line 2,508 ⟶ 3,437:
end
io.write( "\n" )
end</langsyntaxhighlight>
{{out}}
<pre>1 0 0 -8
Line 2,516 ⟶ 3,445:
=={{header|M2000 Interpreter}}==
low bound 1 for array
<syntaxhighlight lang="m2000 interpreter">
<lang M2000 Interpreter>
Module Base1 {
dim base 1, A(3, 4)
Line 2,562 ⟶ 3,491:
}
Base1
</syntaxhighlight>
</lang>
 
Low bound 0 for array
 
<syntaxhighlight lang="m2000 interpreter">
<lang M2000 Interpreter>
Module base0 {
dim base 0, A(3, 4)
Line 2,612 ⟶ 3,541:
}
base0
</syntaxhighlight>
</lang>
 
=={{header|Maple}}==
 
<syntaxhighlight lang="maple">
<lang Maple>
with(LinearAlgebra):
 
ReducedRowEchelonForm(<<1,2,-2>|<2,3,0>|<-1,-1,-3>|<-4,-11,22>>);
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 2,630 ⟶ 3,559:
</pre>
 
=={{header|Mathematica}}/{{header|Wolfram Language}}==
<langsyntaxhighlight Mathematicalang="mathematica">RowReduce[{{1, 2, -1, -4}, {2, 3, -1, -11}, {-2, 0, -3, 22}}]</langsyntaxhighlight>
{{out}}
gives back:
<lang Mathematicapre>{{1, 0, 0, -8}, {0, 1, 0, 1}, {0, 0, 1, -2}}</langpre>
 
=={{header|MATLAB}}==
<langsyntaxhighlight MATLABlang="matlab">rref([1, 2, -1, -4; 2, 3, -1, -11; -2, 0, -3, 22])</langsyntaxhighlight>
 
=={{header|Maxima}}==
<langsyntaxhighlight lang="maxima">rref(a):=block([p,q,k],[p,q]:matrix_size(a),a:echelon(a),
k:min(p,q),
for i thru min(p,q) do (if a[i,i]=0 then (k:i-1,return())),
Line 2,652 ⟶ 3,581:
 
rref(a);
matrix([1,0,0,0,1/2],[0,1,0,0,-1],[0,0,1,0,-1/2],[0,0,0,1,1],[0,0,0,0,0])</langsyntaxhighlight>
 
=={{header|Nim}}==
===Using rationals===
To avoid rounding issues, we can use rationals and convert to floats only at the end.
<langsyntaxhighlight Nimlang="nim">import rationals, strutils
 
type Fraction = Rational[int]
Line 2,752 ⟶ 3,681:
runTest(m2)
runTest(m3)
runTest(m4)</langsyntaxhighlight>
 
{{out}}
Line 2,808 ⟶ 3,737:
===Using floats===
When using floats, we have to be careful when doing comparisons. The previous program adapted to use floats instead of rationals may give wrong results. This would be the case with the second matrix. To get the right result, we have to do a comparison to an epsilon rather than zero. Here is the program modified to work with floats:
<langsyntaxhighlight Nimlang="nim">import strutils, strformat
 
const Eps = 1e-10
Line 2,901 ⟶ 3,830:
runTest(m2)
runTest(m3)
runTest(m4)</langsyntaxhighlight>
 
{{Out}}
Line 2,907 ⟶ 3,836:
 
=={{header|Objeck}}==
<langsyntaxhighlight lang="objeck">
class RowEchelon {
function : Main(args : String[]) ~ Nil {
Line 2,976 ⟶ 3,905:
}
}
</syntaxhighlight>
</lang>
 
=={{header|OCaml}}==
<langsyntaxhighlight OCamllang="ocaml">let swap_rows m i j =
let tmp = m.(i) in
m.(i) <- m.(j);
Line 3,029 ⟶ 3,958:
) row;
print_newline()
) m</langsyntaxhighlight>
 
Another implementation:
<langsyntaxhighlight OCamllang="ocaml">let rref m =
let nr, nc = Array.length m, Array.length m.(0) in
let add r s k =
Line 3,059 ⟶ 3,988:
print_newline();
rref mat;
show mat</langsyntaxhighlight>
 
=={{header|Octave}}==
<langsyntaxhighlight lang="octave">A = [ 1, 2, -1, -4; 2, 3, -1, -11; -2, 0, -3, 22];
refA = rref(A);
disp(refA);</langsyntaxhighlight>
 
=={{header|PARI/GP}}==
PARI has a built-in matrix type, but no commands for row-echelon form. This Ais dimension-limiteda basic one canimplementing be constructed from the builtGauss-in <code>matsolve</code>Jordan command:reduction.
<langsyntaxhighlight lang="parigp">rrefmatrref(M)={
{
my(s=matsize(M),t=s[1]);
for(i=1,s[2],
if(M[t,i]==0, next);
M[t,] /= M[t,i];
for(j=1,t-1,
M[j,] -= M[j,i]*M[t,]
);
for(j=t+1,s[1],
M[j,] -= M[j,i]*M[t,]
);
if(t--<1,break)
);
M;
}
addhelp(matrref, "matrref(M): Returns the reduced row-echelon form of the matrix M.");</syntaxhighlight>
 
A faster, dimension-limited one can be constructed from the built-in <code>matsolve</code> command:
<syntaxhighlight lang="parigp">rref(M)={
my(d=matsize(M));
if(d[1]+1 != d[2], error("Bad size in rref"), d=d[1]);
concat(matid(d), matsolve(matrix(d,d,x,y,M[x,y]), M[,d+1]))
};</langsyntaxhighlight>
Example:
<langsyntaxhighlight lang="parigp">rref([1,2,-1,-4;2,3,-1,-11;-2,0,-3,22])</langsyntaxhighlight>
{{out}}
<pre>%1 =
Line 3,086 ⟶ 4,034:
{{trans|Python}}
Note that the function defined here takes an array reference, which is modified in place.
<langsyntaxhighlight lang="perl">sub rref
{our @m; local *m = shift;
@m or return;
Line 3,122 ⟶ 4,070:
 
rref(\@m);
print display(\@m);</langsyntaxhighlight>
{{out}}
<pre> 1 0 0 -8
Line 3,130 ⟶ 4,078:
=={{header|Phix}}==
{{Trans|Euphoria}}
<!--<langsyntaxhighlight Phixlang="phix">(phixonline)-->
<span style="color: #008080;">with</span> <span style="color: #008080;">javascript_semantics</span>
<span style="color: #008080;">function</span> <span style="color: #000000;">ToReducedRowEchelonForm</span><span style="color: #0000FF;">(</span><span style="color: #004080;">sequence</span> <span style="color: #000000;">M</span><span style="color: #0000FF;">)</span>
Line 3,165 ⟶ 4,113:
<span style="color: #0000FF;">{</span> <span style="color: #000000;">2</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">3</span><span style="color: #0000FF;">,</span> <span style="color: #0000FF;">-</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span> <span style="color: #0000FF;">-</span><span style="color: #000000;">11</span> <span style="color: #0000FF;">},</span>
<span style="color: #0000FF;">{</span> <span style="color: #0000FF;">-</span><span style="color: #000000;">2</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">0</span><span style="color: #0000FF;">,</span> <span style="color: #0000FF;">-</span><span style="color: #000000;">3</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">22</span> <span style="color: #0000FF;">}</span> <span style="color: #0000FF;">})</span>
<!--</langsyntaxhighlight>-->
{{out}}
<pre>
Line 3,174 ⟶ 4,122:
{{works with|PHP|5.x}}
{{trans|Java}}
<langsyntaxhighlight lang="php"><?php
 
function rref($matrix)
Line 3,220 ⟶ 4,168:
return $matrix;
}
?></langsyntaxhighlight>
 
=={{header|PicoLisp}}==
<langsyntaxhighlight PicoLisplang="picolisp">(de reducedRowEchelonForm (Mat)
(let (Lead 1 Cols (length (car Mat)))
(for (X Mat X (cdr X))
Line 3,245 ⟶ 4,193:
(car X) ) ) ) )
(T (> (inc 'Lead) Cols)) ) )
Mat )</langsyntaxhighlight>
{{out}}
<pre>(reducedRowEchelonForm
Line 3,253 ⟶ 4,201:
=={{header|Python}}==
 
<langsyntaxhighlight lang="python">def ToReducedRowEchelonForm( M):
if not M: return
lead = 0
Line 3,287 ⟶ 4,235:
 
for rw in mtx:
print ', '.join( (str(rv) for rv in rw) )</langsyntaxhighlight>
 
=={{header|R}}==
{{trans|Fortran}}
<langsyntaxhighlight lang="rsplus">rref <- function(m) {
pivot <- 1
norow <- nrow(m)
Line 3,323 ⟶ 4,271:
-2, 0, -3, 22), 3, 4, byrow=TRUE)
print(m)
print(rref(m))</langsyntaxhighlight>
 
=={{header|Racket}}==
<langsyntaxhighlight lang="racket">
#lang racket
(require math)
Line 3,336 ⟶ 4,284:
[2 3 -1 -11]
[-2 0 -3 22]]))
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 3,347 ⟶ 4,295:
=={{header|Raku}}==
(formerly Perl 6)
{{trans|Perl}}
{{works with|Rakudo|2018.03}}
<lang perl6>sub rref (@m) {
return unless @m;
my ($lead, $rows, $cols) = 0, +@m, +@m[0];
 
=== Following pseudocode ===
{{trans|Perl}}
<syntaxhighlight lang="raku" line>sub rref (@m) {
my ($lead, $rows, $cols) = 0, @m, @m[0];
for ^$rows -> $r {
return @m unless $lead < $cols or return @m;
my $i = $r;
until @m[$i;$lead] {
next unless ++$i == $rows or next;
$i = $r;
return @m if ++$lead == $cols and return @m;
}
@m[$i, $r] = @m[$r, $i] if $r != $i;
my@m[$r] »/=» $lv = @m[$r;$lead];
 
@m[$r] »/=» $lv;
for ^$rows -> $n {
next if $n == $r;
@m[$n] »-=» @m[$r] »*×» (@m[$n;$lead] // 0);
}
++$lead;
Line 3,375 ⟶ 4,322:
sub rat-or-int ($num) {
return $num unless $num ~~ Rat;
return $num.narrow if $num.narrow.WHAT ~~ Int;
$num.nude.join: '/';
}
Line 3,427 ⟶ 4,374:
say_it( 'Reduced Row Echelon Form Matrix', rref(@matrix) );
say "\n";
}</langsyntaxhighlight>
 
Raku handles rational numbers internally as a ratio of two integers
Line 3,435 ⟶ 4,382:
 
{{out}}
<pre style="height:70ex">
<pre>
Original Matrix
1 2 -1 -4
Line 3,445 ⟶ 4,392:
0 1 0 1
0 0 1 -2
 
 
 
Original Matrix
Line 3,457 ⟶ 4,402:
0 1 0 -217/6
0 0 1 -125/6
 
 
 
Original Matrix
Line 3,473 ⟶ 4,416:
0 0 0 0 0 0
0 0 0 0 0 0
 
 
 
Original Matrix
Line 3,515 ⟶ 4,456:
</pre>
 
=== Row operations, procedural code ===
Re-implemented without the pseudocode, expressed as elementary matrix row operations. See
Re-implemented as elementary matrix row operations. Follow links for background on
http://unapologetic.wordpress.com/2009/08/27/elementary-row-and-column-operations/
[http://unapologetic.wordpress.com/2009/08/27/elementary-row-and-column-operations/ row operations]
and
[http://unapologetic.wordpress.com/2009/09/03/reduced-row-echelon-form/ reduced row echelon form]
 
<syntaxhighlight lang="raku" line>sub scale-row ( @M, \scale, \r ) { @M[r] = @M[r] »×» scale }
First, a procedural version:
<lang perl6>sub swap_rows shear-row ( @M, \scale, $\r1, $\r2 ) { @M[ $r1,] $r2= @M[r1] =»+» ( @M[ $r2,] $r1»×» ]scale ) };
sub scale_row reduce-row ( @M, $scale, $r ) { @M[$\r] = , \c ) { scale-row @M, 1/@M[$r;c], »*» $scale r };
sub shear_row clear-column ( @M, $scale, $r1 \r, $r2 \c ) { shear-row @M[$r1] =, -@M[$r1_;c].list, »+»$_, (r for @M[$r2].keys.grep: »*» $scale!= )r };
sub reduce_row ( @M, $r, $c ) { scale_row( @M, 1/@M[$r][$c], $r ) };
sub clear_column ( @M, $r, $c ) {
for @M.keys.grep( * != $r ) -> $row_num {
shear_row( @M, -1*@M[$row_num][$c], $row_num, $r );
}
}
 
my @M = (
Line 3,537 ⟶ 4,473:
);
 
my $column_countcolumn-count = +@( @M[0] );
my $col = 0;
 
for @M.keys -> $row {
my $current_col = 0;
reduce-row( @M, $row, $col );
while all( @M».[$current_col] ) == 0 {
clear-column( @M, $row, $col );
$current_col++;
returnlast if ++$current_colcol == $column_countcolumn-count; # Matrix was all-zeros.
}
 
say @$_».fmt(' %4g') for @M;</syntaxhighlight>
for @M.keys -> $current_row {
{{out}}
reduce_row( @M, $current_row, $current_col );
<pre>[ 1 0 0 -8]
clear_column( @M, $current_row, $current_col );
[ 0 1 0 1]
$current_col++;
[ 0 0 1 -2]</pre>
return if $current_col == $column_count;
}
 
=== Row operations, object-oriented code ===
say @($_)».fmt(' %4g') for @M;</lang>
The same code as previous section, recast into OO. Also, scale and shear are recast as unscale and unshear, which fit the problem better.
 
<syntaxhighlight lang="raku" line>class Matrix is Array {
And the same code, recast into OO. Also, scale and shear are recast as unscale and unshear, which fit the problem better.
method unscale-row ( @M: \scale, \row ) { @M[row] = @M[row] »/» scale }
<lang perl6>class Matrix is Array {
method unscale_row unshear-row ( @M: $\scale, $row\r1, \r2 ) { @M[r1] = @M[r1] »-» @M[r2] »×» scale }
method reduce-row ( @M[$: \row], =\col ) { @M.unscale-row( @M[$row;col], »/»row $scale;) }
method clear-column ( @M: \row, \col ) { @M.unshear-row( @M[$_;col], $_, row ) for @M.keys.grep: * != row }
}
method unshear_row ( @M: $scale, $r1, $r2 ) {
@M[$r1] = @M[$r1] »-» ( @M[$r2] »*» $scale );
}
method reduce_row ( @M: $row, $col ) {
@M.unscale_row( @M[$row][$col], $row );
}
method clear_column ( @M: $row, $col ) {
for @M.keys.grep( * != $row ) -> $scanning_row {
@M.unshear_row( @M[$scanning_row][$col], $scanning_row, $row );
}
}
method reduced_row_echelon_form ( @M: ) {
my $column_count = +@( @M[0] );
 
my $current_col = 0;
# Skip past all-zero columns.
while all( @M».[$current_col] ) == 0 {
$current_col++;
return if $current_col == $column_count; # Matrix was all-zeros.
}
 
method reduced-row-echelon-form ( @M: ) {
for @M.keys -> $current_row {
my $column-count = @M.reduce_row( $current_row, $current_col )[0];
@M.clear_column(my $current_row,col $current_col= )0;
for @M.keys -> $current_col++;row {
return@M.reduce-row( if $current_col ==row, $column_countcol );
@M.clear-column( $row, $col );
return if ++$col == $column-count;
}
}
Line 3,595 ⟶ 4,512:
);
 
$M.reduced-row-echelon-form;
$M.reduced_row_echelon_form;
say @$_».fmt(' %4g') for @$M;</syntaxhighlight>
 
{{out}}
say @($_)».fmt(' %4g') for @($M);</lang>
<pre>[ 1 0 0 -8]
 
[ 0 1 0 1]
Note that both versions can be simplified using Z+=, Z-=, X*=,
[ 0 0 1 -2]</pre>
and X/= to scale and shear.
Currently, Rakudo has a bug related to Xop= and Zop=.
 
Note that the negative zeros in the output are innocuous,
and also occur in the Perl 5 version.
 
=={{header|REXX}}==
''Reduced Row Echelon Form'' &nbsp; (a.k.a. &nbsp; ''row canonical form'') &nbsp; of a matrix, with optimization added.
<langsyntaxhighlight lang="rexx">/*REXX pgm performs Reduced Row Echelon Form (RREF), AKA row canonical form on a matrix)*/
cols= 0; w= 0; @. =0 /*max cols in a row; max width; matrix.*/
mat.=; mat.1= ' 1 2 -1 -4 '
Line 3,654 ⟶ 4,567:
end /*c*/
say _ /*display a matrix row to the terminal.*/
end /*r*/; return</langsyntaxhighlight>
{{out|output|text=&nbsp; when using the default (internal) input:}}
<pre>
Line 3,671 ⟶ 4,584:
 
=={{header|Ring}}==
<langsyntaxhighlight lang="ring">
# Project : Reduced row echelon form
 
Line 3,729 ⟶ 4,642:
lead = lead + 1
next
</syntaxhighlight>
</lang>
Output:
<pre>
Line 3,735 ⟶ 4,648:
0 1 0 1
0 0 1 -2
</pre>
 
=={{header|RPL}}==
The <code>RREF</code> built-in intruction is available for HP-48G and newer models.
[[1 2 -1 -4] [2 3 -1 -11] [-2 0 -3 22]] RREF
{{out}}
<pre>
1: [[ 1 0 0 -8 ]
[ 0 1 0 1 ]
[ 0 0 1 -2 ]]
</pre>
 
=={{header|Ruby}}==
{{works with|Ruby|1.9.3}}
<langsyntaxhighlight lang="ruby"># returns an 2-D array where each element is a Rational
def reduced_row_echelon_form(ary)
lead = 0
Line 3,809 ⟶ 4,732:
reduced = reduced_row_echelon_form(mtx)
print_matrix reduced
print_matrix convert_to(reduced, :to_f)</langsyntaxhighlight>
 
{{out}}
Line 3,824 ⟶ 4,747:
0.0 0.0 1.0 1.0
</pre>
 
=={{header|Rust}}==
{{trans|FORTRAN}}
I have tried to avoid state mutation with respect to the input matrix and adopt as functional a style as possible in this translation, so for larger matrices one may want to consider memory usage implications.
<langsyntaxhighlight lang="rust">
fn main() {
let mut matrix_to_reduce: Vec<Vec<f64>> = vec![vec![1.0, 2.0 , -1.0, -4.0],
Line 3,846 ⟶ 4,770:
let column_count = matrix_out[0].len();
'outer: for r in 0..row_count {
if column_count <= pivot {
break;
Line 3,858 ⟶ 4,782:
if column_count == pivot {
pivot = pivot - 1;
break 'outer;
}
}
Line 3,885 ⟶ 4,809:
matrix_out
}
</syntaxhighlight>
</lang>
Output:
<pre>
Line 3,893 ⟶ 4,817:
[[1.0, 0.0, 0.0, -8.0], [-0.0, 1.0, 0.0, 1.0], [-0.0, -0.0, 1.0, -2.0]]
</pre>
 
=={{header|Sage}}==
{{works with|Sage|4.6.2}}
<langsyntaxhighlight lang="sage">sage: m = matrix(ZZ, [[1,2,-1,-4],[2,3,-1,-11],[-2,0,-3,22]])
sage: m.rref()
[ 1 0 0 -8]
[ 0 1 0 1]
[ 0 0 1 -2] </langsyntaxhighlight>
 
=={{header|Scheme}}==
{{Works with|Scheme|R<math>^5</math>RS}}
<langsyntaxhighlight lang="scheme">(define (reduced-row-echelon-form matrix)
(define (clean-down matrix from-row column)
(cons (car matrix)
Line 3,950 ⟶ 4,875:
indices)
indices)
indices)))</langsyntaxhighlight>
Example:
<langsyntaxhighlight lang="scheme">(define matrix
(list (list 1 2 -1 -4) (list 2 3 -1 -11) (list -2 0 -3 22)))
 
(display (reduced-row-echelon-form matrix))
(newline)</langsyntaxhighlight>
{{out}}
<syntaxhighlight lang="text">((1 0 0 -8) (0 1 0 1) (0 0 1 -2))</langsyntaxhighlight>
 
=={{header|Seed7}}==
<langsyntaxhighlight lang="seed7">const type: matrix is array array float;
 
const proc: toReducedRowEchelonForm (inout matrix: mat) is func
Line 4,014 ⟶ 4,939:
end for;
end for;
end func;</langsyntaxhighlight>
 
Original source: [http://seed7.sourceforge.net/algorith/math.htm#toReducedRowEchelonForm]
Line 4,020 ⟶ 4,945:
=={{header|Sidef}}==
{{trans|Raku}}
<langsyntaxhighlight lang="ruby">func rref (M) {
var (j, rows, cols) = (0, M.len, M[0].len)
Line 4,077 ⟶ 5,002:
say_it('Reduced Row Echelon Form Matrix', rref(matrix));
say '';
}</langsyntaxhighlight>
{{out}}
<pre>
Line 4,118 ⟶ 5,043:
 
=={{header|Swift}}==
<syntaxhighlight lang="swift">
<lang Swift>
var lead = 0
for r in 0..<rows {
Line 4,155 ⟶ 5,080:
lead += 1
}
</syntaxhighlight>
</lang>
 
=={{header|Tcl}}==
Using utility procs defined at [[Matrix Transpose#Tcl]]
<langsyntaxhighlight lang="tcl">package require Tcl 8.5
namespace path {::tcl::mathop ::tcl::mathfunc}
 
Line 4,207 ⟶ 5,132:
set m {{1 2 -1 -4} {2 3 -1 -11} {-2 0 -3 22}}
print_matrix $m
print_matrix [toRREF $m]</langsyntaxhighlight>
{{out}}
<pre> 1 2 -1 -4
Line 4,218 ⟶ 5,143:
=={{header|TI-83 BASIC}}==
Builtin function: rref()
<langsyntaxhighlight lang="ti83">rref([[1,2,-1,-4][2,3,-1,-11][-2,0,-3,22]])</langsyntaxhighlight>
{{out}}
<pre>
Line 4,227 ⟶ 5,152:
 
=={{header|TI-89 BASIC}}==
<langsyntaxhighlight lang="ti89b">rref([1,2,–1,–4; 2,3,–1,–11; –2,0,–3,22])</langsyntaxhighlight>
 
Output (in prettyprint mode): <math>\begin{bmatrix} 1&0&0&-8 \\ 0&1&0&1 \\ 0&0&1&-2 \end{bmatrix}</math>
Line 4,248 ⟶ 5,173:
These are all combined in the main rref function.
 
<langsyntaxhighlight Ursalalang="ursala">#import std
#import flo
 
Line 4,264 ⟶ 5,189:
<1.,2.,-1.,-4.>,
<2.,3.,-1.,-11.>,
<-2.,0.,-3.,22.>></langsyntaxhighlight>
{{out}}
<pre>
Line 4,275 ⟶ 5,200:
This solution is applicable only if the input
is a non-singular augmented square matrix.
<langsyntaxhighlight Ursalalang="ursala">#import lin
 
rref = @ySzSX msolve; ^plrNCTS\~& ~&iiDlSzyCK9+ :/1.+ 0.!*t</langsyntaxhighlight>
 
=={{header|VBA}}==
{{trans|Phix}}<langsyntaxhighlight lang="vb">Private Function ToReducedRowEchelonForm(M As Variant) As Variant
Dim lead As Integer: lead = 0
Dim rowCount As Integer: rowCount = UBound(M)
Line 4,331 ⟶ 5,256:
Debug.Print Join(r(i), vbTab)
Next i
End Sub</langsyntaxhighlight>{{out}}
<pre>1 0 0 -8
0 1 0 1
Line 4,338 ⟶ 5,263:
=={{header|Visual FoxPro}}==
Translation of Fortran.
<langsyntaxhighlight lang="vfp">
CLOSE DATABASES ALL
LOCAL lnRows As Integer, lnCols As Integer, lcSafety As String
Line 4,429 ⟶ 5,354:
ACOPY(m1, m2, e1, n, e2)
ENDPROC
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 4,442 ⟶ 5,367:
{{libheader|Wren-matrix}}
The above module has a method for this built in as it's needed to implement matrix inversion using the Gauss-Jordan method. However, as in the example here, it's not just restricted to square matrices.
<langsyntaxhighlight ecmascriptlang="wren">import "./matrix" for Matrix
import "./fmt" for Fmt
 
var m = Matrix.new([
Line 4,455 ⟶ 5,380:
System.print("\nRREF:\n")
m.toReducedRowEchelonForm
Fmt.mprint(m, 3, 0)</langsyntaxhighlight>
 
{{out}}
Line 4,471 ⟶ 5,396:
| 0 0 1 -2|
</pre>
 
=={{header|XPL0}}==
<syntaxhighlight lang "XPL0">proc ReducedRowEchelonForm(M, Rows, Cols);
\Replace M with its reduced row echelon form
real M; int Rows, Cols;
int Lead, R, C, I;
real RLead, ILead, T;
[Lead:= 0;
for R:= 0 to Rows-1 do
[if Lead >= Cols then return;
I:= R;
while M(I, Lead) = 0. do
[I:= I+1;
if I = Rows-1 then
[I:= R;
Lead:= Lead+1;
if Lead = Cols-1 then return;
];
];
\Swap rows I and R
T:= M(I); M(I):= M(R); M(R):= T;
 
if M(R, Lead) # 0. then
\Divide row R by M[R, Lead]
[RLead:= M(R, Lead);
for C:= 0 to Cols-1 do
M(R, C):= M(R, C) / RLead;
];
 
for I:= 0 to Rows-1 do
[if I # R then
\Subtract M[I, Lead] multiplied by row R from row I
[ILead:= M(I, Lead);
for C:= 0 to Cols-1 do
M(I, C):= M(I, C) - ILead * M(R, C);
];
];
Lead:= Lead+1;
];
];
 
real M;
int R, C;
[M:= [ [ 1., 2., -1., -4.],
[ 2., 3., -1.,-11.],
[-2., 0., -3., 22.] ];
ReducedRowEchelonForm(M, 3, 4);
Format(4,1);
for R:= 0 to 3-1 do
[for C:= 0 to 4-1 do
RlOut(0, M(R,C));
CrLf(0);
];
]</syntaxhighlight>
{{out}}
<pre>
1.0 0.0 0.0 -8.0
0.0 1.0 0.0 1.0
0.0 0.0 1.0 -2.0
</pre>
 
=={{header|Yabasic}}==
<syntaxhighlight lang="yabasic">// Rosetta Code problem: https://rosettacode.org/wiki/Reduced_row_echelon_form
// by Jjuanhdez, 06/2022
 
dim matrix (3, 4)
matrix(1, 1) = 1 : matrix(1, 2) = 2 : matrix(1, 3) = -1 : matrix(1, 4) = -4
matrix(2, 1) = 2 : matrix(2, 2) = 3 : matrix(2, 3) = -1 : matrix(2, 4) = -11
matrix(3, 1) = -2 : matrix(3, 2) = 0 : matrix(3, 3) = -3 : matrix(3, 4) = 22
 
RREF (matrix())
 
for row = 1 to 3
for col = 1 to 4
if matrix(row, col) = 0 then
print "0", chr$(9);
else
print matrix(row, col), chr$(9);
end if
next
print
next
end
 
sub RREF(x())
local nrows, ncols, lead, r, i, j, n
nrows = arraysize(matrix(), 1) //3
ncols = arraysize(matrix(), 2) //4
lead = 1
for r = 1 to nrows
if lead >= ncols break
i = r
while matrix(i, lead) = 0
i = i + 1
if i = nrows then
i = r
lead = lead + 1
if lead = ncols break 2
end if
wend
for j = 1 to ncols
temp = matrix(i, j)
matrix(i, j) = matrix(r, j)
matrix(r, j) = temp
next
n = matrix(r, lead)
if n <> 0 then
for j = 1 to ncols
matrix(r, j) = matrix(r, j) / n
next
end if
for i = 1 to nrows
if i <> r then
n = matrix(i, lead)
for j = 1 to ncols
matrix(i, j) = matrix(i, j) - matrix(r, j) * n
next
end if
next
lead = lead + 1
next
end sub</syntaxhighlight>
 
=={{header|zkl}}==
The "best" way is to use the GNU Scientific Library:
<langsyntaxhighlight lang="zkl">var [const] GSL=Import("zklGSL"); // libGSL (GNU Scientific Library)
fcn toReducedRowEchelonForm(M){ // in place
lead,rows,columns := 0,M.rows,M.cols;
Line 4,493 ⟶ 5,540:
}
M
}</langsyntaxhighlight>
<langsyntaxhighlight lang="zkl">A:=GSL.Matrix(3,4).set( 1, 2, -1, -4,
2, 3, -1, -11,
-2, 0, -3, 22);
toReducedRowEchelonForm(A).format(5,1).println();</langsyntaxhighlight>
{{out}}
<pre>
Line 4,506 ⟶ 5,553:
Or, using lists of lists and direct implementation of the pseudo-code given,
lots of generating new rows rather than modifying the rows themselves.
<langsyntaxhighlight lang="zkl">fcn toReducedRowEchelonForm(m){ // m is modified, the rows are not
lead,rowCount,columnCount := 0,m.len(),m[1].len();
foreach r in (rowCount){
Line 4,527 ⟶ 5,574:
}//foreach
m
}</langsyntaxhighlight>
<langsyntaxhighlight lang="zkl">m:=List( T( 1, 2, -1, -4,), // T is read only list
T( 2, 3, -1, -11,),
T(-2, 0, -3, 22,));
Line 4,536 ⟶ 5,583:
 
fcn printM(m){ m.pump(Console.println,rowFmt) }
fcn rowFmt(row){ ("%4d "*row.len()).fmt(row.xplode()) }</langsyntaxhighlight>
{{out}}
<pre>
2,053

edits