Reduced row echelon form: Difference between revisions

Content added Content deleted
m (syntax highlighting fixup automation)
Line 59: Line 59:
{{trans|Python}}
{{trans|Python}}


<lang 11l>F ToReducedRowEchelonForm(&M)
<syntaxhighlight lang="11l">F ToReducedRowEchelonForm(&M)
V lead = 0
V lead = 0
V rowCount = M.len
V rowCount = M.len
Line 90: Line 90:


L(rw) mtx
L(rw) mtx
print(rw.join(‘, ’))</lang>
print(rw.join(‘, ’))</syntaxhighlight>


{{out}}
{{out}}
Line 101: Line 101:
=={{header|360 Assembly}}==
=={{header|360 Assembly}}==
{{trans|BBC BASIC}}
{{trans|BBC BASIC}}
<lang 360asm>* reduced row echelon form 27/08/2015
<syntaxhighlight lang="360asm">* reduced row echelon form 27/08/2015
RREF CSECT
RREF CSECT
USING RREF,R12
USING RREF,R12
Line 258: Line 258:
PG DC CL48' '
PG DC CL48' '
YREGS
YREGS
END RREF</lang>
END RREF</syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>
Line 271: Line 271:
Therefore return this statements are returning the Matrix object itself.
Therefore return this statements are returning the Matrix object itself.


<lang Actionscript>public function RREF():Matrix {
<syntaxhighlight lang="actionscript">public function RREF():Matrix {
var lead:uint, i:uint, j:uint, r:uint = 0;
var lead:uint, i:uint, j:uint, r:uint = 0;


Line 307: Line 307:
}
}
return this;
return this;
}</lang>
}</syntaxhighlight>


=={{header|Ada}}==
=={{header|Ada}}==
matrices.ads:
matrices.ads:
<lang Ada>generic
<syntaxhighlight lang="ada">generic
type Element_Type is private;
type Element_Type is private;
Zero : Element_Type;
Zero : Element_Type;
Line 321: Line 321:
array (Positive range <>, Positive range <>) of Element_Type;
array (Positive range <>, Positive range <>) of Element_Type;
function Reduced_Row_Echelon_form (Source : Matrix) return Matrix;
function Reduced_Row_Echelon_form (Source : Matrix) return Matrix;
end Matrices;</lang>
end Matrices;</syntaxhighlight>


matrices.adb:
matrices.adb:
<lang Ada>package body Matrices is
<syntaxhighlight lang="ada">package body Matrices is
procedure Swap_Rows (From : in out Matrix; First, Second : in Positive) is
procedure Swap_Rows (From : in out Matrix; First, Second : in Positive) is
Temporary : Element_Type;
Temporary : Element_Type;
Line 394: Line 394:
return Result;
return Result;
end Reduced_Row_Echelon_form;
end Reduced_Row_Echelon_form;
end Matrices;</lang>
end Matrices;</syntaxhighlight>


Example use: main.adb:
Example use: main.adb:
<lang Ada>with Matrices;
<syntaxhighlight lang="ada">with Matrices;
with Ada.Text_IO;
with Ada.Text_IO;
procedure Main is
procedure Main is
Line 424: Line 424:
Ada.Text_IO.Put_Line ("reduced to:");
Ada.Text_IO.Put_Line ("reduced to:");
Print_Matrix (Reduced);
Print_Matrix (Reduced);
end Main;</lang>
end Main;</syntaxhighlight>


{{out}}
{{out}}
Line 436: Line 436:


=={{header|Aime}}==
=={{header|Aime}}==
<lang aime>rref(list l, integer rows, columns)
<syntaxhighlight lang="aime">rref(list l, integer rows, columns)
{
{
integer e, f, i, j, lead, r;
integer e, f, i, j, lead, r;
Line 502: Line 502:


0;
0;
}</lang>
}</syntaxhighlight>
{{Out}}
{{Out}}
<pre> 1 0 0 -8
<pre> 1 0 0 -8
Line 513: Line 513:
{{works with|ALGOL 68G|Any - tested with release mk15-0.8b.fc9.i386}}
{{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 }} -->
<!-- {{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 }} -->
<lang algol68>MODE FIELD = REAL; # FIELD can be REAL, LONG REAL etc, or COMPL, FRAC etc #
<syntaxhighlight lang="algol68">MODE FIELD = REAL; # FIELD can be REAL, LONG REAL etc, or COMPL, FRAC etc #
MODE VEC = [0]FIELD;
MODE VEC = [0]FIELD;
MODE MAT = [0,0]FIELD;
MODE MAT = [0,0]FIELD;
Line 566: Line 566:
mat repr = $"("n(1 UPB mat-1)(f(vec repr)", "lx)f(vec repr)")"$;
mat repr = $"("n(1 UPB mat-1)(f(vec repr)", "lx)f(vec repr)")"$;


printf((mat repr, mat, $l$))</lang>
printf((mat repr, mat, $l$))</syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>
Line 576: Line 576:
=={{header|ALGOL W}}==
=={{header|ALGOL W}}==
From the pseudo code.
From the pseudo code.
<lang algolw>begin
<syntaxhighlight lang="algolw">begin
% replaces M with it's reduced row echelon form %
% replaces M with it's reduced row echelon form %
% M should have bounds ( 0 :: rMax, 0 :: cMax ) %
% M should have bounds ( 0 :: rMax, 0 :: cMax ) %
Line 635: Line 635:
end for_r
end for_r
end
end
end.</lang>
end.</syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>
Line 644: Line 644:


=={{header|AutoHotkey}}==
=={{header|AutoHotkey}}==
<lang AutoHotkey>ToReducedRowEchelonForm(M){
<syntaxhighlight lang="autohotkey">ToReducedRowEchelonForm(M){
rowCount := M.Count() ; the number of rows in M
rowCount := M.Count() ; the number of rows in M
columnCount := M.1.Count() ; the number of columns in M
columnCount := M.1.Count() ; the number of columns in M
Line 680: Line 680:
}
}
return M
return M
}</lang>
}</syntaxhighlight>
Examples:<lang AutoHotkey>M := [[1 , 2, -1, -4 ]
Examples:<syntaxhighlight lang="autohotkey">M := [[1 , 2, -1, -4 ]
, [2 , 3, -1, -11]
, [2 , 3, -1, -11]
, [-2, 0, -3, 22]]
, [-2, 0, -3, 22]]
Line 693: Line 693:
}
}
MsgBox % output
MsgBox % output
return</lang>
return</syntaxhighlight>
{{out}}
{{out}}
<pre>1 0 0 -8
<pre>1 0 0 -8
Line 701: Line 701:


=={{header|AutoIt}}==
=={{header|AutoIt}}==
<syntaxhighlight lang="autoit">
<lang AutoIt>
Global $ivMatrix[3][4] = [[1, 2, -1, -4],[2, 3, -1, -11],[-2, 0, -3, 22]]
Global $ivMatrix[3][4] = [[1, 2, -1, -4],[2, 3, -1, -11],[-2, 0, -3, 22]]
ToReducedRowEchelonForm($ivMatrix)
ToReducedRowEchelonForm($ivMatrix)
Line 754: Line 754:
Return $matrix
Return $matrix
EndFunc ;==>ToReducedRowEchelonForm
EndFunc ;==>ToReducedRowEchelonForm
</syntaxhighlight>
</lang>
{{out}}
{{out}}
<pre>[1,0,0,-8]
<pre>[1,0,0,-8]
Line 761: Line 761:


=={{header|BASIC256}}==
=={{header|BASIC256}}==
<lang BASIC256>arraybase 1
<syntaxhighlight lang="basic256">arraybase 1
global matrix
global matrix
dim matrix = {{1, 2, -1, -4}, {2, 3, -1, -11}, { -2, 0, -3, 22}}
dim matrix = {{1, 2, -1, -4}, {2, 3, -1, -11}, { -2, 0, -3, 22}}
Line 815: Line 815:
lead += 1
lead += 1
next
next
end subroutine</lang>
end subroutine</syntaxhighlight>




=={{header|BBC BASIC}}==
=={{header|BBC BASIC}}==
{{works with|BBC BASIC for Windows}}
{{works with|BBC BASIC for Windows}}
<lang bbcbasic> DIM matrix(2,3)
<syntaxhighlight lang="bbcbasic"> DIM matrix(2,3)
matrix() = 1, 2, -1, -4, \
matrix() = 1, 2, -1, -4, \
\ 2, 3, -1, -11, \
\ 2, 3, -1, -11, \
Line 861: Line 861:
lead% += 1
lead% += 1
NEXT r%
NEXT r%
ENDPROC</lang>
ENDPROC</syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>
Line 870: Line 870:


=={{header|C}}==
=={{header|C}}==
<lang c>#include <stdio.h>
<syntaxhighlight lang="c">#include <stdio.h>
#define TALLOC(n,typ) malloc(n*sizeof(typ))
#define TALLOC(n,typ) malloc(n*sizeof(typ))


Line 1,025: Line 1,025:
MtxDisplay(m1);
MtxDisplay(m1);
return 0;
return 0;
}</lang>
}</syntaxhighlight>


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


namespace rref
namespace rref
Line 1,087: Line 1,087:
}
}
}
}
}</lang>
}</syntaxhighlight>


=={{header|C++}}==
=={{header|C++}}==
Line 1,095: Line 1,095:


{{works with|g++|4.1.2 20061115 (prerelease) (Debian 4.1.1-21)}}
{{works with|g++|4.1.2 20061115 (prerelease) (Debian 4.1.1-21)}}
<lang cpp>#include <algorithm> // for std::swap
<syntaxhighlight lang="cpp">#include <algorithm> // for std::swap
#include <cstddef>
#include <cstddef>
#include <cassert>
#include <cassert>
Line 1,280: Line 1,280:


return EXIT_SUCCESS;
return EXIT_SUCCESS;
}</lang>
}</syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>
Line 1,290: Line 1,290:
=={{header|Common Lisp}}==
=={{header|Common Lisp}}==
Direct implementation of the pseudo-code given.
Direct implementation of the pseudo-code given.
<lang lisp>(defun convert-to-row-echelon-form (matrix)
<syntaxhighlight lang="lisp">(defun convert-to-row-echelon-form (matrix)
(let* ((dimensions (array-dimensions matrix))
(let* ((dimensions (array-dimensions matrix))
(row-count (first dimensions))
(row-count (first dimensions))
Line 1,333: Line 1,333:
(* scale (aref matrix r c))))))
(* scale (aref matrix r c))))))
(incf lead))
(incf lead))
:finally (return matrix)))))</lang>
:finally (return matrix)))))</syntaxhighlight>


=={{header|D}}==
=={{header|D}}==
<lang d>import std.stdio, std.algorithm, std.array, std.conv;
<syntaxhighlight lang="d">import std.stdio, std.algorithm, std.array, std.conv;


void toReducedRowEchelonForm(T)(T[][] M) pure nothrow @nogc {
void toReducedRowEchelonForm(T)(T[][] M) pure nothrow @nogc {
Line 1,377: Line 1,377:
A.toReducedRowEchelonForm;
A.toReducedRowEchelonForm;
writefln("%(%(%2d %)\n%)", A);
writefln("%(%(%2d %)\n%)", A);
}</lang>
}</syntaxhighlight>
{{out}}
{{out}}
<pre> 1 0 0 -8
<pre> 1 0 0 -8
Line 1,384: Line 1,384:


=={{header|Euphoria}}==
=={{header|Euphoria}}==
<lang euphoria>function ToReducedRowEchelonForm(sequence M)
<syntaxhighlight lang="euphoria">function ToReducedRowEchelonForm(sequence M)
integer lead,rowCount,columnCount,i
integer lead,rowCount,columnCount,i
sequence temp
sequence temp
Line 1,422: Line 1,422:
{ { 1, 2, -1, -4 },
{ { 1, 2, -1, -4 },
{ 2, 3, -1, -11 },
{ 2, 3, -1, -11 },
{ -2, 0, -3, 22 } })</lang>
{ -2, 0, -3, 22 } })</syntaxhighlight>


{{out}}
{{out}}
Line 1,432: Line 1,432:


=={{header|Factor}}==
=={{header|Factor}}==
<lang factor>USE: math.matrices.elimination
<syntaxhighlight lang="factor">USE: math.matrices.elimination
{ { 1 2 -1 -4 } { 2 3 -1 -11 } { -2 0 -3 22 } } solution .</lang>
{ { 1 2 -1 -4 } { 2 3 -1 -11 } { -2 0 -3 22 } } solution .</syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>
Line 1,440: Line 1,440:


=={{header|Fortran}}==
=={{header|Fortran}}==
<lang fortran>module Rref
<syntaxhighlight lang="fortran">module Rref
implicit none
implicit none
contains
contains
Line 1,478: Line 1,478:
deallocate(trow)
deallocate(trow)
end subroutine to_rref
end subroutine to_rref
end module Rref</lang>
end module Rref</syntaxhighlight>


<lang fortran>program prg_test
<syntaxhighlight lang="fortran">program prg_test
use rref
use rref
implicit none
implicit none
Line 1,502: Line 1,502:
end do
end do


end program prg_test</lang>
end program prg_test</syntaxhighlight>


=={{header|FreeBASIC}}==
=={{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.
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.


<lang freebasic>#include once "matmult.bas"
<syntaxhighlight lang="freebasic">#include once "matmult.bas"


sub rowswap( byval M as Matrix, i as uinteger, j as uinteger )
sub rowswap( byval M as Matrix, i as uinteger, j as uinteger )
Line 1,567: Line 1,567:
next j
next j
print
print
next i</lang>
next i</syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>
Line 1,578: Line 1,578:
===2D representation===
===2D representation===
From WP pseudocode:
From WP pseudocode:
<lang go>package main
<syntaxhighlight lang="go">package main


import "fmt"
import "fmt"
Line 1,636: Line 1,636:
lead++
lead++
}
}
}</lang>
}</syntaxhighlight>
{{out}} (not so pretty, sorry)
{{out}} (not so pretty, sorry)
<pre>
<pre>
Line 1,649: Line 1,649:


===Flat representation===
===Flat representation===
<lang go>package main
<syntaxhighlight lang="go">package main


import "fmt"
import "fmt"
Line 1,731: Line 1,731:
m.rref()
m.rref()
m.print("Reduced:")
m.print("Reduced:")
}</lang>
}</syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>
Line 1,750: Line 1,750:
Options are provided for both ''partial pivoting'' and ''scaled partial pivoting''.
Options are provided for both ''partial pivoting'' and ''scaled partial pivoting''.
The default option is no pivoting at all.
The default option is no pivoting at all.
<lang groovy>enum Pivoting {
<syntaxhighlight lang="groovy">enum Pivoting {
NONE({ i, it -> 1 }),
NONE({ i, it -> 1 }),
PARTIAL({ i, it -> - (it[i].abs()) }),
PARTIAL({ i, it -> - (it[i].abs()) }),
Line 1,781: Line 1,781:
}
}
matrix
matrix
}</lang>
}</syntaxhighlight>


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.
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.
<lang groovy>def matrixCopy = { matrix -> matrix.collect { row -> row.collect { it } } }
<syntaxhighlight lang="groovy">def matrixCopy = { matrix -> matrix.collect { row -> row.collect { it } } }


println "Tests for matrix A:"
println "Tests for matrix A:"
Line 1,829: Line 1,829:
println "pivoting == Pivoting.SCALED"
println "pivoting == Pivoting.SCALED"
reducedRowEchelonForm(matrixCopy(b), Pivoting.SCALED).each { println it }
reducedRowEchelonForm(matrixCopy(b), Pivoting.SCALED).each { println it }
println()</lang>
println()</syntaxhighlight>


{{out}}
{{out}}
Line 1,873: Line 1,873:
This program was produced by translating from the Python and gradually refactoring the result into a more functional style.
This program was produced by translating from the Python and gradually refactoring the result into a more functional style.


<lang haskell>import Data.List (find)
<syntaxhighlight lang="haskell">import Data.List (find)


rref :: Fractional a => [[a]] -> [[a]]
rref :: Fractional a => [[a]] -> [[a]]
Line 1,904: Line 1,904:
{- Replaces the element at the given index. -}
{- Replaces the element at the given index. -}
replace n e l = a ++ e : b
replace n e l = a ++ e : b
where (a, _ : b) = splitAt n l</lang>
where (a, _ : b) = splitAt n l</syntaxhighlight>


=={{header|Icon}} and {{header|Unicon}}==
=={{header|Icon}} and {{header|Unicon}}==


Works in both languages:
Works in both languages:
<lang unicon>procedure main(A)
<syntaxhighlight lang="unicon">procedure main(A)
tM := [[ 1, 2, -1, -4],
tM := [[ 1, 2, -1, -4],
[ 2, 3, -1,-11],
[ 2, 3, -1,-11],
Line 1,941: Line 1,941:
procedure showMat(M)
procedure showMat(M)
every r := !M do every writes(right(!r,5)||" " | "\n")
every r := !M do every writes(right(!r,5)||" " | "\n")
end</lang>
end</syntaxhighlight>


{{out}}
{{out}}
Line 1,956: Line 1,956:


'''Solution:'''
'''Solution:'''
<lang j>NB.*pivot v Pivot at row, column
<syntaxhighlight lang="j">NB.*pivot v Pivot at row, column
NB. form: (row,col) pivot M
NB. form: (row,col) pivot M
pivot=: dyad define
pivot=: dyad define
Line 1,991: Line 1,991:
end.
end.
mtx
mtx
)</lang>
)</syntaxhighlight>


'''Usage:'''
'''Usage:'''
<lang j> require 'math/misc/linear'
<syntaxhighlight lang="j"> require 'math/misc/linear'
]A=: 1 2 _1 _4 , 2 3 _1 _11 ,: _2 0 _3 22
]A=: 1 2 _1 _4 , 2 3 _1 _11 ,: _2 0 _3 22
1 2 _1 _4
1 2 _1 _4
Line 2,003: Line 2,003:
1 0 0 _8
1 0 0 _8
0 1 0 1
0 1 0 1
0 0 1 _2</lang>
0 0 1 _2</syntaxhighlight>


Additional examples, recommended on talk page:
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
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
1 0 0 0 _1
Line 2,023: Line 2,023:
1 0
1 0
0 1
0 1
0 0</lang>
0 0</syntaxhighlight>


And:
And:


<lang j>mat=: 0 ". ];._2 noun define
<syntaxhighlight 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 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
1 0 0 0 0 0 0 1 0 0 0 0 _1 0 0 0 0 0
Line 2,063: Line 2,063:
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 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 1 0 1
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0.820513</lang>
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0.820513</syntaxhighlight>


=={{header|Java}}==
=={{header|Java}}==
''This requires Apache Commons 2.2+''
''This requires Apache Commons 2.2+''
<lang java>import java.util.*;
<syntaxhighlight lang="java">import java.util.*;
import java.lang.Math;
import java.lang.Math;
import org.apache.commons.math.fraction.Fraction;
import org.apache.commons.math.fraction.Fraction;
Line 2,326: Line 2,326:
System.out.println("after\n" + a.toString() + "\n");
System.out.println("after\n" + a.toString() + "\n");
}
}
}</lang>
}</syntaxhighlight>


=={{header|JavaScript}}==
=={{header|JavaScript}}==
{{works with|SpiderMonkey}} for the <code>print()</code> function.
{{works with|SpiderMonkey}} for the <code>print()</code> function.
Extends the Matrix class defined at [[Matrix Transpose#JavaScript]]
Extends the Matrix class defined at [[Matrix Transpose#JavaScript]]
<lang javascript>// modifies the matrix in-place
<syntaxhighlight lang="javascript">// modifies the matrix in-place
Matrix.prototype.toReducedRowEchelonForm = function() {
Matrix.prototype.toReducedRowEchelonForm = function() {
var lead = 0;
var lead = 0;
Line 2,384: Line 2,384:
[ 3, 3, 0, 7]
[ 3, 3, 0, 7]
]);
]);
print(m.toReducedRowEchelonForm());</lang>
print(m.toReducedRowEchelonForm());</syntaxhighlight>
{{out}}
{{out}}
<pre>1,0,0,-8
<pre>1,0,0,-8
Line 2,412: Line 2,412:


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


typealias Matrix = Array<DoubleArray>
typealias Matrix = Array<DoubleArray>
Line 2,491: Line 2,491:
m.printf("Reduced row echelon form:")
m.printf("Reduced row echelon form:")
}
}
}</lang>
}</syntaxhighlight>


{{out}}
{{out}}
Line 2,521: Line 2,521:


=={{header|Lua}}==
=={{header|Lua}}==
<lang lua>function ToReducedRowEchelonForm ( M )
<syntaxhighlight lang="lua">function ToReducedRowEchelonForm ( M )
local lead = 1
local lead = 1
local n_rows, n_cols = #M, #M[1]
local n_rows, n_cols = #M, #M[1]
Line 2,566: Line 2,566:
end
end
io.write( "\n" )
io.write( "\n" )
end</lang>
end</syntaxhighlight>
{{out}}
{{out}}
<pre>1 0 0 -8
<pre>1 0 0 -8
Line 2,574: Line 2,574:
=={{header|M2000 Interpreter}}==
=={{header|M2000 Interpreter}}==
low bound 1 for array
low bound 1 for array
<syntaxhighlight lang="m2000 interpreter">
<lang M2000 Interpreter>
Module Base1 {
Module Base1 {
dim base 1, A(3, 4)
dim base 1, A(3, 4)
Line 2,620: Line 2,620:
}
}
Base1
Base1
</syntaxhighlight>
</lang>


Low bound 0 for array
Low bound 0 for array


<syntaxhighlight lang="m2000 interpreter">
<lang M2000 Interpreter>
Module base0 {
Module base0 {
dim base 0, A(3, 4)
dim base 0, A(3, 4)
Line 2,670: Line 2,670:
}
}
base0
base0
</syntaxhighlight>
</lang>


=={{header|Maple}}==
=={{header|Maple}}==


<syntaxhighlight lang="maple">
<lang Maple>
with(LinearAlgebra):
with(LinearAlgebra):


ReducedRowEchelonForm(<<1,2,-2>|<2,3,0>|<-1,-1,-3>|<-4,-11,22>>);
ReducedRowEchelonForm(<<1,2,-2>|<2,3,0>|<-1,-1,-3>|<-4,-11,22>>);
</syntaxhighlight>
</lang>
{{out}}
{{out}}
<pre>
<pre>
Line 2,689: Line 2,689:


=={{header|Mathematica}}/{{header|Wolfram Language}}==
=={{header|Mathematica}}/{{header|Wolfram Language}}==
<lang Mathematica>RowReduce[{{1, 2, -1, -4}, {2, 3, -1, -11}, {-2, 0, -3, 22}}]</lang>
<syntaxhighlight lang="mathematica">RowReduce[{{1, 2, -1, -4}, {2, 3, -1, -11}, {-2, 0, -3, 22}}]</syntaxhighlight>
{{out}}
{{out}}
<pre>{{1, 0, 0, -8}, {0, 1, 0, 1}, {0, 0, 1, -2}}</pre>
<pre>{{1, 0, 0, -8}, {0, 1, 0, 1}, {0, 0, 1, -2}}</pre>


=={{header|MATLAB}}==
=={{header|MATLAB}}==
<lang MATLAB>rref([1, 2, -1, -4; 2, 3, -1, -11; -2, 0, -3, 22])</lang>
<syntaxhighlight lang="matlab">rref([1, 2, -1, -4; 2, 3, -1, -11; -2, 0, -3, 22])</syntaxhighlight>


=={{header|Maxima}}==
=={{header|Maxima}}==
<lang maxima>rref(a):=block([p,q,k],[p,q]:matrix_size(a),a:echelon(a),
<syntaxhighlight lang="maxima">rref(a):=block([p,q,k],[p,q]:matrix_size(a),a:echelon(a),
k:min(p,q),
k:min(p,q),
for i thru min(p,q) do (if a[i,i]=0 then (k:i-1,return())),
for i thru min(p,q) do (if a[i,i]=0 then (k:i-1,return())),
Line 2,710: Line 2,710:


rref(a);
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])</lang>
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])</syntaxhighlight>


=={{header|Nim}}==
=={{header|Nim}}==
===Using rationals===
===Using rationals===
To avoid rounding issues, we can use rationals and convert to floats only at the end.
To avoid rounding issues, we can use rationals and convert to floats only at the end.
<lang Nim>import rationals, strutils
<syntaxhighlight lang="nim">import rationals, strutils


type Fraction = Rational[int]
type Fraction = Rational[int]
Line 2,810: Line 2,810:
runTest(m2)
runTest(m2)
runTest(m3)
runTest(m3)
runTest(m4)</lang>
runTest(m4)</syntaxhighlight>


{{out}}
{{out}}
Line 2,866: Line 2,866:
===Using floats===
===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:
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:
<lang Nim>import strutils, strformat
<syntaxhighlight lang="nim">import strutils, strformat


const Eps = 1e-10
const Eps = 1e-10
Line 2,959: Line 2,959:
runTest(m2)
runTest(m2)
runTest(m3)
runTest(m3)
runTest(m4)</lang>
runTest(m4)</syntaxhighlight>


{{Out}}
{{Out}}
Line 2,965: Line 2,965:


=={{header|Objeck}}==
=={{header|Objeck}}==
<lang objeck>
<syntaxhighlight lang="objeck">
class RowEchelon {
class RowEchelon {
function : Main(args : String[]) ~ Nil {
function : Main(args : String[]) ~ Nil {
Line 3,034: Line 3,034:
}
}
}
}
</syntaxhighlight>
</lang>


=={{header|OCaml}}==
=={{header|OCaml}}==
<lang OCaml>let swap_rows m i j =
<syntaxhighlight lang="ocaml">let swap_rows m i j =
let tmp = m.(i) in
let tmp = m.(i) in
m.(i) <- m.(j);
m.(i) <- m.(j);
Line 3,087: Line 3,087:
) row;
) row;
print_newline()
print_newline()
) m</lang>
) m</syntaxhighlight>


Another implementation:
Another implementation:
<lang OCaml>let rref m =
<syntaxhighlight lang="ocaml">let rref m =
let nr, nc = Array.length m, Array.length m.(0) in
let nr, nc = Array.length m, Array.length m.(0) in
let add r s k =
let add r s k =
Line 3,117: Line 3,117:
print_newline();
print_newline();
rref mat;
rref mat;
show mat</lang>
show mat</syntaxhighlight>


=={{header|Octave}}==
=={{header|Octave}}==
<lang octave>A = [ 1, 2, -1, -4; 2, 3, -1, -11; -2, 0, -3, 22];
<syntaxhighlight lang="octave">A = [ 1, 2, -1, -4; 2, 3, -1, -11; -2, 0, -3, 22];
refA = rref(A);
refA = rref(A);
disp(refA);</lang>
disp(refA);</syntaxhighlight>


=={{header|PARI/GP}}==
=={{header|PARI/GP}}==
PARI has a built-in matrix type, but no commands for row-echelon form. This is a basic one implementing Gauss-Jordan reduction.
PARI has a built-in matrix type, but no commands for row-echelon form. This is a basic one implementing Gauss-Jordan reduction.
<lang parigp>matrref(M)=
<syntaxhighlight lang="parigp">matrref(M)=
{
{
my(s=matsize(M),t=s[1]);
my(s=matsize(M),t=s[1]);
Line 3,142: Line 3,142:
M;
M;
}
}
addhelp(matrref, "matrref(M): Returns the reduced row-echelon form of the matrix M.");</lang>
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:
A faster, dimension-limited one can be constructed from the built-in <code>matsolve</code> command:
<lang parigp>rref(M)={
<syntaxhighlight lang="parigp">rref(M)={
my(d=matsize(M));
my(d=matsize(M));
if(d[1]+1 != d[2], error("Bad size in rref"), d=d[1]);
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]))
concat(matid(d), matsolve(matrix(d,d,x,y,M[x,y]), M[,d+1]))
};</lang>
};</syntaxhighlight>
Example:
Example:
<lang parigp>rref([1,2,-1,-4;2,3,-1,-11;-2,0,-3,22])</lang>
<syntaxhighlight lang="parigp">rref([1,2,-1,-4;2,3,-1,-11;-2,0,-3,22])</syntaxhighlight>
{{out}}
{{out}}
<pre>%1 =
<pre>%1 =
Line 3,163: Line 3,163:
{{trans|Python}}
{{trans|Python}}
Note that the function defined here takes an array reference, which is modified in place.
Note that the function defined here takes an array reference, which is modified in place.
<lang perl>sub rref
<syntaxhighlight lang="perl">sub rref
{our @m; local *m = shift;
{our @m; local *m = shift;
@m or return;
@m or return;
Line 3,199: Line 3,199:


rref(\@m);
rref(\@m);
print display(\@m);</lang>
print display(\@m);</syntaxhighlight>
{{out}}
{{out}}
<pre> 1 0 0 -8
<pre> 1 0 0 -8
Line 3,207: Line 3,207:
=={{header|Phix}}==
=={{header|Phix}}==
{{Trans|Euphoria}}
{{Trans|Euphoria}}
<!--<lang Phix>(phixonline)-->
<!--<syntaxhighlight lang="phix">(phixonline)-->
<span style="color: #008080;">with</span> <span style="color: #008080;">javascript_semantics</span>
<span style="color: #008080;">with</span> <span style="color: #008080;">javascript_semantics</span>
<span style="color: #008080;">function</span> <span style="color: #000000;">ToReducedRowEchelonForm</span><span style="color: #0000FF;">(</span><span style="color: #004080;">sequence</span> <span style="color: #000000;">M</span><span style="color: #0000FF;">)</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,242: Line 3,242:
<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: #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>
<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>
<!--</lang>-->
<!--</syntaxhighlight>-->
{{out}}
{{out}}
<pre>
<pre>
Line 3,251: Line 3,251:
{{works with|PHP|5.x}}
{{works with|PHP|5.x}}
{{trans|Java}}
{{trans|Java}}
<lang php><?php
<syntaxhighlight lang="php"><?php


function rref($matrix)
function rref($matrix)
Line 3,297: Line 3,297:
return $matrix;
return $matrix;
}
}
?></lang>
?></syntaxhighlight>


=={{header|PicoLisp}}==
=={{header|PicoLisp}}==
<lang PicoLisp>(de reducedRowEchelonForm (Mat)
<syntaxhighlight lang="picolisp">(de reducedRowEchelonForm (Mat)
(let (Lead 1 Cols (length (car Mat)))
(let (Lead 1 Cols (length (car Mat)))
(for (X Mat X (cdr X))
(for (X Mat X (cdr X))
Line 3,322: Line 3,322:
(car X) ) ) ) )
(car X) ) ) ) )
(T (> (inc 'Lead) Cols)) ) )
(T (> (inc 'Lead) Cols)) ) )
Mat )</lang>
Mat )</syntaxhighlight>
{{out}}
{{out}}
<pre>(reducedRowEchelonForm
<pre>(reducedRowEchelonForm
Line 3,330: Line 3,330:
=={{header|Python}}==
=={{header|Python}}==


<lang python>def ToReducedRowEchelonForm( M):
<syntaxhighlight lang="python">def ToReducedRowEchelonForm( M):
if not M: return
if not M: return
lead = 0
lead = 0
Line 3,364: Line 3,364:


for rw in mtx:
for rw in mtx:
print ', '.join( (str(rv) for rv in rw) )</lang>
print ', '.join( (str(rv) for rv in rw) )</syntaxhighlight>


=={{header|R}}==
=={{header|R}}==
{{trans|Fortran}}
{{trans|Fortran}}
<lang rsplus>rref <- function(m) {
<syntaxhighlight lang="rsplus">rref <- function(m) {
pivot <- 1
pivot <- 1
norow <- nrow(m)
norow <- nrow(m)
Line 3,400: Line 3,400:
-2, 0, -3, 22), 3, 4, byrow=TRUE)
-2, 0, -3, 22), 3, 4, byrow=TRUE)
print(m)
print(m)
print(rref(m))</lang>
print(rref(m))</syntaxhighlight>


=={{header|Racket}}==
=={{header|Racket}}==
<lang racket>
<syntaxhighlight lang="racket">
#lang racket
#lang racket
(require math)
(require math)
Line 3,413: Line 3,413:
[2 3 -1 -11]
[2 3 -1 -11]
[-2 0 -3 22]]))
[-2 0 -3 22]]))
</syntaxhighlight>
</lang>
{{out}}
{{out}}
<pre>
<pre>
Line 3,427: Line 3,427:
=== Following pseudocode ===
=== Following pseudocode ===
{{trans|Perl}}
{{trans|Perl}}
<lang perl6>sub rref (@m) {
<syntaxhighlight lang="raku" line>sub rref (@m) {
my ($lead, $rows, $cols) = 0, @m, @m[0];
my ($lead, $rows, $cols) = 0, @m, @m[0];
for ^$rows -> $r {
for ^$rows -> $r {
Line 3,503: Line 3,503:
say_it( 'Reduced Row Echelon Form Matrix', rref(@matrix) );
say_it( 'Reduced Row Echelon Form Matrix', rref(@matrix) );
say "\n";
say "\n";
}</lang>
}</syntaxhighlight>


Raku handles rational numbers internally as a ratio of two integers
Raku handles rational numbers internally as a ratio of two integers
Line 3,591: Line 3,591:
[http://unapologetic.wordpress.com/2009/09/03/reduced-row-echelon-form/ reduced row echelon form]
[http://unapologetic.wordpress.com/2009/09/03/reduced-row-echelon-form/ reduced row echelon form]


<lang perl6>sub scale-row ( @M, \scale, \r ) { @M[r] = @M[r] »×» scale }
<syntaxhighlight lang="raku" line>sub scale-row ( @M, \scale, \r ) { @M[r] = @M[r] »×» scale }
sub shear-row ( @M, \scale, \r1, \r2 ) { @M[r1] = @M[r1] »+» ( @M[r2] »×» scale ) }
sub shear-row ( @M, \scale, \r1, \r2 ) { @M[r1] = @M[r1] »+» ( @M[r2] »×» scale ) }
sub reduce-row ( @M, \r, \c ) { scale-row @M, 1/@M[r;c], r }
sub reduce-row ( @M, \r, \c ) { scale-row @M, 1/@M[r;c], r }
Line 3,610: Line 3,610:
}
}


say @$_».fmt(' %4g') for @M;</lang>
say @$_».fmt(' %4g') for @M;</syntaxhighlight>
{{out}}
{{out}}
<pre>[ 1 0 0 -8]
<pre>[ 1 0 0 -8]
Line 3,618: Line 3,618:
=== Row operations, object-oriented code ===
=== Row operations, object-oriented code ===
The same code as previous section, recast into OO. Also, scale and shear are recast as unscale and unshear, which fit the problem better.
The same code as previous section, recast into OO. Also, scale and shear are recast as unscale and unshear, which fit the problem better.
<lang perl6>class Matrix is Array {
<syntaxhighlight lang="raku" line>class Matrix is Array {
method unscale-row ( @M: \scale, \row ) { @M[row] = @M[row] »/» scale }
method unscale-row ( @M: \scale, \row ) { @M[row] = @M[row] »/» scale }
method unshear-row ( @M: \scale, \r1, \r2 ) { @M[r1] = @M[r1] »-» @M[r2] »×» scale }
method unshear-row ( @M: \scale, \r1, \r2 ) { @M[r1] = @M[r1] »-» @M[r2] »×» scale }
Line 3,642: Line 3,642:


$M.reduced-row-echelon-form;
$M.reduced-row-echelon-form;
say @$_».fmt(' %4g') for @$M;</lang>
say @$_».fmt(' %4g') for @$M;</syntaxhighlight>
{{out}}
{{out}}
<pre>[ 1 0 0 -8]
<pre>[ 1 0 0 -8]
Line 3,650: Line 3,650:
=={{header|REXX}}==
=={{header|REXX}}==
''Reduced Row Echelon Form'' &nbsp; (a.k.a. &nbsp; ''row canonical form'') &nbsp; of a matrix, with optimization added.
''Reduced Row Echelon Form'' &nbsp; (a.k.a. &nbsp; ''row canonical form'') &nbsp; of a matrix, with optimization added.
<lang rexx>/*REXX pgm performs Reduced Row Echelon Form (RREF), AKA row canonical form on a matrix)*/
<syntaxhighlight 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.*/
cols= 0; w= 0; @. =0 /*max cols in a row; max width; matrix.*/
mat.=; mat.1= ' 1 2 -1 -4 '
mat.=; mat.1= ' 1 2 -1 -4 '
Line 3,696: Line 3,696:
end /*c*/
end /*c*/
say _ /*display a matrix row to the terminal.*/
say _ /*display a matrix row to the terminal.*/
end /*r*/; return</lang>
end /*r*/; return</syntaxhighlight>
{{out|output|text=&nbsp; when using the default (internal) input:}}
{{out|output|text=&nbsp; when using the default (internal) input:}}
<pre>
<pre>
Line 3,713: Line 3,713:


=={{header|Ring}}==
=={{header|Ring}}==
<lang ring>
<syntaxhighlight lang="ring">
# Project : Reduced row echelon form
# Project : Reduced row echelon form


Line 3,771: Line 3,771:
lead = lead + 1
lead = lead + 1
next
next
</syntaxhighlight>
</lang>
Output:
Output:
<pre>
<pre>
Line 3,781: Line 3,781:
=={{header|Ruby}}==
=={{header|Ruby}}==
{{works with|Ruby|1.9.3}}
{{works with|Ruby|1.9.3}}
<lang ruby># returns an 2-D array where each element is a Rational
<syntaxhighlight lang="ruby"># returns an 2-D array where each element is a Rational
def reduced_row_echelon_form(ary)
def reduced_row_echelon_form(ary)
lead = 0
lead = 0
Line 3,851: Line 3,851:
reduced = reduced_row_echelon_form(mtx)
reduced = reduced_row_echelon_form(mtx)
print_matrix reduced
print_matrix reduced
print_matrix convert_to(reduced, :to_f)</lang>
print_matrix convert_to(reduced, :to_f)</syntaxhighlight>


{{out}}
{{out}}
Line 3,869: Line 3,869:
{{trans|FORTRAN}}
{{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.
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.
<lang rust>
<syntaxhighlight lang="rust">
fn main() {
fn main() {
let mut matrix_to_reduce: Vec<Vec<f64>> = vec![vec![1.0, 2.0 , -1.0, -4.0],
let mut matrix_to_reduce: Vec<Vec<f64>> = vec![vec![1.0, 2.0 , -1.0, -4.0],
Line 3,927: Line 3,927:
matrix_out
matrix_out
}
}
</syntaxhighlight>
</lang>
Output:
Output:
<pre>
<pre>
Line 3,938: Line 3,938:
=={{header|Sage}}==
=={{header|Sage}}==
{{works with|Sage|4.6.2}}
{{works with|Sage|4.6.2}}
<lang sage>sage: m = matrix(ZZ, [[1,2,-1,-4],[2,3,-1,-11],[-2,0,-3,22]])
<syntaxhighlight lang="sage">sage: m = matrix(ZZ, [[1,2,-1,-4],[2,3,-1,-11],[-2,0,-3,22]])
sage: m.rref()
sage: m.rref()
[ 1 0 0 -8]
[ 1 0 0 -8]
[ 0 1 0 1]
[ 0 1 0 1]
[ 0 0 1 -2] </lang>
[ 0 0 1 -2] </syntaxhighlight>


=={{header|Scheme}}==
=={{header|Scheme}}==
{{Works with|Scheme|R<math>^5</math>RS}}
{{Works with|Scheme|R<math>^5</math>RS}}
<lang scheme>(define (reduced-row-echelon-form matrix)
<syntaxhighlight lang="scheme">(define (reduced-row-echelon-form matrix)
(define (clean-down matrix from-row column)
(define (clean-down matrix from-row column)
(cons (car matrix)
(cons (car matrix)
Line 3,993: Line 3,993:
indices)
indices)
indices)
indices)
indices)))</lang>
indices)))</syntaxhighlight>
Example:
Example:
<lang scheme>(define matrix
<syntaxhighlight lang="scheme">(define matrix
(list (list 1 2 -1 -4) (list 2 3 -1 -11) (list -2 0 -3 22)))
(list (list 1 2 -1 -4) (list 2 3 -1 -11) (list -2 0 -3 22)))


(display (reduced-row-echelon-form matrix))
(display (reduced-row-echelon-form matrix))
(newline)</lang>
(newline)</syntaxhighlight>
{{out}}
{{out}}
<lang>((1 0 0 -8) (0 1 0 1) (0 0 1 -2))</lang>
<syntaxhighlight lang="text">((1 0 0 -8) (0 1 0 1) (0 0 1 -2))</syntaxhighlight>


=={{header|Seed7}}==
=={{header|Seed7}}==
<lang seed7>const type: matrix is array array float;
<syntaxhighlight lang="seed7">const type: matrix is array array float;


const proc: toReducedRowEchelonForm (inout matrix: mat) is func
const proc: toReducedRowEchelonForm (inout matrix: mat) is func
Line 4,057: Line 4,057:
end for;
end for;
end for;
end for;
end func;</lang>
end func;</syntaxhighlight>


Original source: [http://seed7.sourceforge.net/algorith/math.htm#toReducedRowEchelonForm]
Original source: [http://seed7.sourceforge.net/algorith/math.htm#toReducedRowEchelonForm]
Line 4,063: Line 4,063:
=={{header|Sidef}}==
=={{header|Sidef}}==
{{trans|Raku}}
{{trans|Raku}}
<lang ruby>func rref (M) {
<syntaxhighlight lang="ruby">func rref (M) {
var (j, rows, cols) = (0, M.len, M[0].len)
var (j, rows, cols) = (0, M.len, M[0].len)
Line 4,120: Line 4,120:
say_it('Reduced Row Echelon Form Matrix', rref(matrix));
say_it('Reduced Row Echelon Form Matrix', rref(matrix));
say '';
say '';
}</lang>
}</syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>
Line 4,161: Line 4,161:


=={{header|Swift}}==
=={{header|Swift}}==
<syntaxhighlight lang="swift">
<lang Swift>
var lead = 0
var lead = 0
for r in 0..<rows {
for r in 0..<rows {
Line 4,198: Line 4,198:
lead += 1
lead += 1
}
}
</syntaxhighlight>
</lang>


=={{header|Tcl}}==
=={{header|Tcl}}==
Using utility procs defined at [[Matrix Transpose#Tcl]]
Using utility procs defined at [[Matrix Transpose#Tcl]]
<lang tcl>package require Tcl 8.5
<syntaxhighlight lang="tcl">package require Tcl 8.5
namespace path {::tcl::mathop ::tcl::mathfunc}
namespace path {::tcl::mathop ::tcl::mathfunc}


Line 4,250: Line 4,250:
set m {{1 2 -1 -4} {2 3 -1 -11} {-2 0 -3 22}}
set m {{1 2 -1 -4} {2 3 -1 -11} {-2 0 -3 22}}
print_matrix $m
print_matrix $m
print_matrix [toRREF $m]</lang>
print_matrix [toRREF $m]</syntaxhighlight>
{{out}}
{{out}}
<pre> 1 2 -1 -4
<pre> 1 2 -1 -4
Line 4,261: Line 4,261:
=={{header|TI-83 BASIC}}==
=={{header|TI-83 BASIC}}==
Builtin function: rref()
Builtin function: rref()
<lang ti83>rref([[1,2,-1,-4][2,3,-1,-11][-2,0,-3,22]])</lang>
<syntaxhighlight lang="ti83">rref([[1,2,-1,-4][2,3,-1,-11][-2,0,-3,22]])</syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>
Line 4,270: Line 4,270:


=={{header|TI-89 BASIC}}==
=={{header|TI-89 BASIC}}==
<lang ti89b>rref([1,2,–1,–4; 2,3,–1,–11; –2,0,–3,22])</lang>
<syntaxhighlight lang="ti89b">rref([1,2,–1,–4; 2,3,–1,–11; –2,0,–3,22])</syntaxhighlight>


Output (in prettyprint mode): <math>\begin{bmatrix} 1&0&0&-8 \\ 0&1&0&1 \\ 0&0&1&-2 \end{bmatrix}</math>
Output (in prettyprint mode): <math>\begin{bmatrix} 1&0&0&-8 \\ 0&1&0&1 \\ 0&0&1&-2 \end{bmatrix}</math>
Line 4,291: Line 4,291:
These are all combined in the main rref function.
These are all combined in the main rref function.


<lang Ursala>#import std
<syntaxhighlight lang="ursala">#import std
#import flo
#import flo


Line 4,307: Line 4,307:
<1.,2.,-1.,-4.>,
<1.,2.,-1.,-4.>,
<2.,3.,-1.,-11.>,
<2.,3.,-1.,-11.>,
<-2.,0.,-3.,22.>></lang>
<-2.,0.,-3.,22.>></syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>
Line 4,318: Line 4,318:
This solution is applicable only if the input
This solution is applicable only if the input
is a non-singular augmented square matrix.
is a non-singular augmented square matrix.
<lang Ursala>#import lin
<syntaxhighlight lang="ursala">#import lin


rref = @ySzSX msolve; ^plrNCTS\~& ~&iiDlSzyCK9+ :/1.+ 0.!*t</lang>
rref = @ySzSX msolve; ^plrNCTS\~& ~&iiDlSzyCK9+ :/1.+ 0.!*t</syntaxhighlight>


=={{header|VBA}}==
=={{header|VBA}}==
{{trans|Phix}}<lang vb>Private Function ToReducedRowEchelonForm(M As Variant) As Variant
{{trans|Phix}}<syntaxhighlight lang="vb">Private Function ToReducedRowEchelonForm(M As Variant) As Variant
Dim lead As Integer: lead = 0
Dim lead As Integer: lead = 0
Dim rowCount As Integer: rowCount = UBound(M)
Dim rowCount As Integer: rowCount = UBound(M)
Line 4,374: Line 4,374:
Debug.Print Join(r(i), vbTab)
Debug.Print Join(r(i), vbTab)
Next i
Next i
End Sub</lang>{{out}}
End Sub</syntaxhighlight>{{out}}
<pre>1 0 0 -8
<pre>1 0 0 -8
0 1 0 1
0 1 0 1
Line 4,381: Line 4,381:
=={{header|Visual FoxPro}}==
=={{header|Visual FoxPro}}==
Translation of Fortran.
Translation of Fortran.
<lang vfp>
<syntaxhighlight lang="vfp">
CLOSE DATABASES ALL
CLOSE DATABASES ALL
LOCAL lnRows As Integer, lnCols As Integer, lcSafety As String
LOCAL lnRows As Integer, lnCols As Integer, lcSafety As String
Line 4,472: Line 4,472:
ACOPY(m1, m2, e1, n, e2)
ACOPY(m1, m2, e1, n, e2)
ENDPROC
ENDPROC
</syntaxhighlight>
</lang>
{{out}}
{{out}}
<pre>
<pre>
Line 4,485: Line 4,485:
{{libheader|Wren-matrix}}
{{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.
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.
<lang ecmascript>import "/matrix" for Matrix
<syntaxhighlight lang="ecmascript">import "/matrix" for Matrix
import "/fmt" for Fmt
import "/fmt" for Fmt


Line 4,498: Line 4,498:
System.print("\nRREF:\n")
System.print("\nRREF:\n")
m.toReducedRowEchelonForm
m.toReducedRowEchelonForm
Fmt.mprint(m, 3, 0)</lang>
Fmt.mprint(m, 3, 0)</syntaxhighlight>


{{out}}
{{out}}
Line 4,516: Line 4,516:


=={{header|Yabasic}}==
=={{header|Yabasic}}==
<lang yabasic>// Rosetta Code problem: https://rosettacode.org/wiki/Reduced_row_echelon_form
<syntaxhighlight lang="yabasic">// Rosetta Code problem: https://rosettacode.org/wiki/Reduced_row_echelon_form
// by Jjuanhdez, 06/2022
// by Jjuanhdez, 06/2022


Line 4,575: Line 4,575:
lead = lead + 1
lead = lead + 1
next
next
end sub</lang>
end sub</syntaxhighlight>


=={{header|zkl}}==
=={{header|zkl}}==
The "best" way is to use the GNU Scientific Library:
The "best" way is to use the GNU Scientific Library:
<lang zkl>var [const] GSL=Import("zklGSL"); // libGSL (GNU Scientific Library)
<syntaxhighlight lang="zkl">var [const] GSL=Import("zklGSL"); // libGSL (GNU Scientific Library)
fcn toReducedRowEchelonForm(M){ // in place
fcn toReducedRowEchelonForm(M){ // in place
lead,rows,columns := 0,M.rows,M.cols;
lead,rows,columns := 0,M.rows,M.cols;
Line 4,598: Line 4,598:
}
}
M
M
}</lang>
}</syntaxhighlight>
<lang zkl>A:=GSL.Matrix(3,4).set( 1, 2, -1, -4,
<syntaxhighlight lang="zkl">A:=GSL.Matrix(3,4).set( 1, 2, -1, -4,
2, 3, -1, -11,
2, 3, -1, -11,
-2, 0, -3, 22);
-2, 0, -3, 22);
toReducedRowEchelonForm(A).format(5,1).println();</lang>
toReducedRowEchelonForm(A).format(5,1).println();</syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>
Line 4,611: Line 4,611:
Or, using lists of lists and direct implementation of the pseudo-code given,
Or, using lists of lists and direct implementation of the pseudo-code given,
lots of generating new rows rather than modifying the rows themselves.
lots of generating new rows rather than modifying the rows themselves.
<lang zkl>fcn toReducedRowEchelonForm(m){ // m is modified, the rows are not
<syntaxhighlight lang="zkl">fcn toReducedRowEchelonForm(m){ // m is modified, the rows are not
lead,rowCount,columnCount := 0,m.len(),m[1].len();
lead,rowCount,columnCount := 0,m.len(),m[1].len();
foreach r in (rowCount){
foreach r in (rowCount){
Line 4,632: Line 4,632:
}//foreach
}//foreach
m
m
}</lang>
}</syntaxhighlight>
<lang zkl>m:=List( T( 1, 2, -1, -4,), // T is read only list
<syntaxhighlight lang="zkl">m:=List( T( 1, 2, -1, -4,), // T is read only list
T( 2, 3, -1, -11,),
T( 2, 3, -1, -11,),
T(-2, 0, -3, 22,));
T(-2, 0, -3, 22,));
Line 4,641: Line 4,641:


fcn printM(m){ m.pump(Console.println,rowFmt) }
fcn printM(m){ m.pump(Console.println,rowFmt) }
fcn rowFmt(row){ ("%4d "*row.len()).fmt(row.xplode()) }</lang>
fcn rowFmt(row){ ("%4d "*row.len()).fmt(row.xplode()) }</syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>