Jump to content

Gauss-Jordan matrix inversion: Difference between revisions

m
syntax highlighting fixup automation
m (→‎{{header|Raku}}: sync up 'rref')
m (syntax highlighting fixup automation)
Line 10:
{{trans|Nim}}
 
<langsyntaxhighlight lang="11l">V Eps = 1e-10
 
F transformToRref(&mat)
Line 92:
runTest(m1)
runTest(m2)
runTest(m3)</langsyntaxhighlight>
 
{{out}}
Line 136:
The COPY file of FORMAT, to format a floating point number, can be found at:
[[360_Assembly_include|Include files 360 Assembly]].
<langsyntaxhighlight lang="360asm">* Gauss-Jordan matrix inversion 17/01/2021
GAUSSJOR CSECT
USING GAUSSJOR,R13 base register
Line 334:
PG DC CL80' ' buffer
REGEQU
END GAUSSJOR </langsyntaxhighlight>
{{out}}
<pre>
Line 346:
=={{header|ALGOL 60}}==
{{works with|A60}}
<langsyntaxhighlight lang="algol60">begin
comment Gauss-Jordan matrix inversion - 22/01/2021;
integer n;
Line 411:
show("c",c)
end
end </langsyntaxhighlight>
{{out}}
<pre>
Line 433:
=={{header|ALGOL 68}}==
{{Trans|ALGOL 60}}
<langsyntaxhighlight lang="algol68">BEGIN # Gauss-Jordan matrix inversion #
PROC rref = ( REF[,]REAL m )VOID:
BEGIN
Line 490:
c := inverse( b );
show( "c", c )
END</langsyntaxhighlight>
{{out}}
<pre>
Line 512:
=={{header|C}}==
{{trans|Fortran}}
<langsyntaxhighlight Clang="c">/*----------------------------------------------------------------------
gjinv - Invert a matrix, Gauss-Jordan algorithm
A is destroyed. Returns 1 for a singular matrix.
Line 575:
}
return 0;
} /* end of gjinv */</langsyntaxhighlight>
Test program:
<langsyntaxhighlight Clang="c">/* Test matrix inversion */
#include <stdio.h>
int main (void)
Line 632:
}
return 0;
} /* end of test program */</langsyntaxhighlight>
Output is the same as the Fortran example.
 
=={{header|C sharp|C#}}==
<langsyntaxhighlight lang="csharp">
using System;
 
Line 827:
}
}
</syntaxhighlight>
</lang>
<langsyntaxhighlight lang="csharp">
using System;
 
Line 843:
}
}
</syntaxhighlight>
</lang>
{{out}}<pre>
-0.913043478260869 0.246376811594203 0.0942028985507246 0.413043478260869
Line 852:
 
=={{header|C++}}==
<langsyntaxhighlight lang="cpp">#include <algorithm>
#include <cassert>
#include <iomanip>
Line 990:
print(std::cout, inverse(inv));
return 0;
}</langsyntaxhighlight>
 
{{out}}
Line 1,015:
Normally you would call <code>recip</code> to calculate the inverse of a matrix, but it uses a different method than Gauss-Jordan, so here's Gauss-Jordan.
{{works with|Factor|0.99 2020-01-23}}
<langsyntaxhighlight lang="factor">USING: kernel math.matrices math.matrices.elimination
prettyprint sequences ;
 
Line 1,043:
{ 7 -8 9 1 }
{ 1 -2 1 3 }
} gauss-jordan-invert simple-table.</langsyntaxhighlight>
{{out}}
<pre>
Line 1,053:
=={{header|Fortran}}==
Note that the Crout algorithm is a more efficient way to invert a matrix.
<langsyntaxhighlight Fortranlang="fortran">!-----------------------------------------------------------------------
! gjinv - Invert a matrix, Gauss-Jordan algorithm
! A is destroyed.
Line 1,157:
 
RETURN
END ! of gjinv</langsyntaxhighlight>
Test program:
{{works with|gfortran|8.3.0}}
<langsyntaxhighlight Fortranlang="fortran">! Test matrix inversion
PROGRAM TINV
IMPLICIT NONE
Line 1,232:
END DO
 
END ! of test program</langsyntaxhighlight>
{{out}}
<pre>
Line 1,267:
The include statements use code from [[Matrix multiplication#FreeBASIC]], which contains the Matrix type used here, and [[Reduced row echelon form#FreeBASIC]] which contains the function for reducing a matrix to row-echelon form. Make sure to take out all the print statements first!
 
<langsyntaxhighlight lang="freebasic">#include once "matmult.bas"
#include once "rowech.bas"
 
Line 1,308:
next j
print
next i</langsyntaxhighlight>
{{out}}
<pre>
Line 1,321:
 
=={{header|Generic}}==
<langsyntaxhighlight lang="cpp">
// The Generic Language is a database compiler. This code is compiled into database then executed out of database.
 
Line 1,993:
 
}
</syntaxhighlight>
</lang>
=={{header|Go}}==
{{trans|Kotlin}}
<langsyntaxhighlight lang="go">package main
 
import "fmt"
Line 2,081:
b := matrix{{2, -1, 0}, {-1, 2, -1}, {0, -1, 2}}
b.inverse().print("Inverse of B is:\n")
}</langsyntaxhighlight>
{{out}}
<pre>
Line 2,098:
===Alternative===
{{trans|PowerShell}}
<langsyntaxhighlight lang="go">package main
import (
Line 2,187:
b := matrix{{2, -1, 0}, {-1, 2, -1}, {0, -1, 2}}
b.inverse().print("Inverse of B is:\n")
}</langsyntaxhighlight>
{{out}}
<pre>Same output than above</pre>
 
=={{header|Haskell}}==
<langsyntaxhighlight Haskelllang="haskell">isMatrix xs = null xs || all ((== (length.head $ xs)).length) xs
 
isSquareMatrix xs = null xs || all ((== (length xs)).length) xs
Line 2,241:
mapM_ print $ inversion a
putStrLn "\ninversion b ="
mapM_ print $ inversion b</langsyntaxhighlight>
{{out}}
<pre>
Line 2,261:
 
Uses Gauss-Jordan implementation (as described in [[Reduced_row_echelon_form#J]]) to find reduced row echelon form of the matrix after augmenting with an identity matrix.
<langsyntaxhighlight lang="j">require 'math/misc/linear'
augmentR_I1=: ,. e.@i.@# NB. augment matrix on the right with its Identity matrix
matrix_invGJ=: # }."1 [: gauss_jordan@augmentR_I1</langsyntaxhighlight>
 
'''Usage:'''
<langsyntaxhighlight lang="j"> ]A =: 1 2 3, 4 1 6,: 7 8 9
1 2 3
4 1 6
Line 2,273:
_0.8125 0.125 0.1875
0.125 _0.25 0.125
0.520833 0.125 _0.145833</langsyntaxhighlight>
 
=={{header|Java}}==
<langsyntaxhighlight lang="java">// GaussJordan.java
 
import java.util.Random;
Line 2,297:
Matrix.product(m, inv).print();
}
}</langsyntaxhighlight>
 
<langsyntaxhighlight lang="java">// Matrix.java
 
public class Matrix {
Line 2,395:
elements[j] = tmp;
}
}</langsyntaxhighlight>
 
{{out}}
Line 2,424:
'''Works with gojq, the Go implementation of jq'''
 
<langsyntaxhighlight lang="jq"># Create an m x n matrix,
# it being understood that:
# matrix(0; _; _) evaluates to []
Line 2,506:
| reduce range(0; $nr) as $i ( matrix($nr; $nr; 0);
reduce range($nr; 2 *$nr) as $j (.;
.[$i][$j - $nr] = $ary[$i][$j] )) ;</langsyntaxhighlight>
'''The Task'''
<langsyntaxhighlight lang="jq">def arrays: [
[ [ 1, 2, 3],
[ 4, 1, 6],
Line 2,532:
;
 
task</langsyntaxhighlight>
{{out}}
<pre>
Line 2,572:
 
'''Built-in''' LAPACK-based linear solver uses partial-pivoted Gauss elimination):
<langsyntaxhighlight lang="julia">A = [1 2 3; 4 1 6; 7 8 9]
@show I / A
@show inv(A)</langsyntaxhighlight>
 
'''Native implementation''':
<langsyntaxhighlight lang="julia">function gaussjordan(A::Matrix)
size(A, 1) == size(A, 2) || throw(ArgumentError("A must be squared"))
n = size(A, 1)
Line 2,632:
 
A = rand(10, 10)
@assert gaussjordan(A) ≈ inv(A)</langsyntaxhighlight>
 
{{out}}
Line 2,641:
=={{header|Kotlin}}==
This follows the description of Gauss-Jordan elimination in Wikipedia whereby the original square matrix is first augmented to the right by its identity matrix, its reduced row echelon form is then found and finally the identity matrix to the left is removed to leave the inverse of the original square matrix.
<langsyntaxhighlight lang="scala">// version 1.2.21
 
typealias Matrix = Array<DoubleArray>
Line 2,730:
)
b.inverse().printf("Inverse of B is :\n")
}</langsyntaxhighlight>
 
{{out}}
Line 2,748:
 
=={{header|Lambdatalk}}==
<langsyntaxhighlight lang="scheme">
{require lib_matrix}
 
Line 2,759:
[1.4444444444444444,-0.5555555555555556,0.1111111111111111],
[-0.05555555555555555,0.1111111111111111,-0.05555555555555555]]
</syntaxhighlight>
</lang>
 
=={{header|Mathematica}} / {{header|Wolfram Language}}==
<langsyntaxhighlight Mathematicalang="mathematica">a = N@{{1, 7, 5, 0}, {5, 8, 6, 9}, {2, 1, 6, 4}, {8, 1, 2, 4}};
elimmat = RowReduce[Join[a, IdentityMatrix[Length[a]], 2]];
inv = elimmat[[All, -Length[a] ;;]]</langsyntaxhighlight>
{{out}}
<pre>{{0.0463243, -0.0563948, -0.0367573, 0.163646}, {0.0866062, 0.0684794, -0.133938, -0.020141}, {0.0694864, -0.0845921, 0.194864, -0.00453172}, {-0.149043, 0.137966, 0.00956697, -0.0699899}}</pre>
 
=={{header|MATLAB}}==
<langsyntaxhighlight MATLABlang="matlab">function GaussInverse(M)
original = M;
[n,~] = size(M);
Line 2,812:
0, -1, 2 ];
 
GaussInverse(A)</langsyntaxhighlight>
 
{{out}}
Line 2,839:
=={{header|Nim}}==
We reuse the algorithm of task https://rosettacode.org/wiki/Reduced_row_echelon_form (version using floats).
<langsyntaxhighlight Nimlang="nim">import strformat, strutils
 
const Eps = 1e-10
Line 2,945:
runTest(m1)
runTest(m2)
runTest(m3)</langsyntaxhighlight>
 
{{out}}
Line 2,984:
=={{header|Perl}}==
Included code from [[Reduced_row_echelon_form#Perl|Reduced row echelon form]] task.
<langsyntaxhighlight lang="perl">sub rref {
our @m; local *m = shift;
@m or return;
Line 3,048:
my @rt = gauss_jordan_invert( @gj );
print "After round-trip:\n" . display(\@rt) . "\n";} . "\n"
}</langsyntaxhighlight>
{{out}}
<pre>Original Matrix:
Line 3,086:
{{trans|Kotlin}}
uses ToReducedRowEchelonForm() from [[Reduced_row_echelon_form#Phix]]
<!--<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,144:
<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;">1</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">2</span><span style="color: #0000FF;">}}</span>
<span style="color: #7060A8;">pp</span><span style="color: #0000FF;">(</span><span style="color: #000000;">inverse</span><span style="color: #0000FF;">(</span><span style="color: #000000;">test</span><span style="color: #0000FF;">),{</span><span style="color: #004600;">pp_Nest</span><span style="color: #0000FF;">,</span><span style="color: #000000;">1</span><span style="color: #0000FF;">})</span>
<!--</langsyntaxhighlight>-->
{{out}}
<pre>
Line 3,154:
===alternate===
{{trans|PowerShell}}
<!--<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;">gauss_jordan_inv</span><span style="color: #0000FF;">(</span><span style="color: #004080;">sequence</span> <span style="color: #000000;">a</span><span style="color: #0000FF;">)</span>
Line 3,200:
<span style="color: #7060A8;">puts</span><span style="color: #0000FF;">(</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"inv(a) = "</span><span style="color: #0000FF;">)</span>
<span style="color: #7060A8;">pp</span><span style="color: #0000FF;">(</span><span style="color: #000000;">inva</span><span style="color: #0000FF;">,{</span><span style="color: #004600;">pp_Nest</span><span style="color: #0000FF;">,</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #004600;">pp_Indent</span><span style="color: #0000FF;">,</span><span style="color: #000000;">9</span><span style="color: #0000FF;">,</span><span style="color: #004600;">pp_FltFmt</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"%4.2f"</span><span style="color: #0000FF;">})</span>
<!--</langsyntaxhighlight>-->
{{out}}
<pre>
Line 3,264:
 
=={{header|PowerShell}}==
<syntaxhighlight lang="powershell">
<lang PowerShell>
function gauss-jordan-inv([double[][]]$a) {
$n = $a.count
Line 3,317:
show $invb
 
</syntaxhighlight>
</lang>
<b>Output:</b>
<pre>
Line 3,345:
Use numpy matrix inversion
 
<langsyntaxhighlight lang="python">
import numpy as np
from numpy.linalg import inv
Line 3,353:
print(a)
print(ainv)
</syntaxhighlight>
</lang>
 
{{out}}
Line 3,369:
Using the matrix library that comes with default Racket installation
 
<langsyntaxhighlight lang="racket">#lang racket
 
(require math/matrix
Line 3,382:
 
(inverse A)
(matrix-inverse A)</langsyntaxhighlight>
 
{{out}}
Line 3,395:
Uses bits and pieces from other tasks, [[Reduced_row_echelon_form#Raku|Reduced row echelon form]] primarily.
 
<syntaxhighlight lang="raku" perl6line>sub gauss-jordan-invert (@m where &is-square) {
^@m .map: { @m[$_].append: identity(+@m)[$_] };
@m.&rref[*]»[+@m .. *];
Line 3,461:
say_it( ' Gauss-Jordan Inverted:', my @invert = gauss-jordan-invert @matrix );
say_it( ' Re-inverted:', gauss-jordan-invert @invert».Array );
}</langsyntaxhighlight>
 
{{out}}
Line 3,590:
=={{header|REXX}}==
===version 1===
<langsyntaxhighlight lang="rexx">/* REXX */
Parse Arg seed nn
If seed='' Then
Line 3,865:
Return bs
 
Exit: Say arg(1)</langsyntaxhighlight>
{{out}} Using the defaults for seed and n
<pre>show 1 The given matrix
Line 3,966:
===version 2===
{{trans|PL/I}}
<langsyntaxhighlight lang="rexx">/*REXX program performs a (square) matrix inversion using the Gauss─Jordan method. */
data= 8 3 7 5 9 12 10 11 6 2 4 13 14 15 16 17 /*the matrix element values. */
call build 4 /*assign data elements to the matrix. */
Line 4,000:
else _= _ right(format(x.r.c, w, f), w + f + length(.))
end /*c*/; say _
end /*r*/; return</langsyntaxhighlight>
{{out|output|text=&nbsp; when using the internal default input:}}
<pre>
Line 4,017:
 
=={{header|Rust}}==
<langsyntaxhighlight lang="rust">
fn main() {
let mut a: Vec<Vec<f64>> = vec![vec![1.0, 2.0, 3.0],
Line 4,131:
}
}
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 4,162:
Uses the '''rref(M)''' function from [https://rosettacode.org/wiki/Reduced_row_echelon_form#Sidef Reduced row echelon form].
{{trans|Raku}}
<langsyntaxhighlight lang="ruby">func gauss_jordan_invert (M) {
 
var I = M.len.of {|i|
Line 4,186:
say gauss_jordan_invert(A).map {
.map { "%6s" % .as_rat }.join(" ")
}.join("\n")</langsyntaxhighlight>
{{out}}
<pre>
Line 4,197:
=={{header|VBA}}==
{{trans|Phix}}
Uses ToReducedRowEchelonForm() from [[Reduced_row_echelon_form#VBA]]<langsyntaxhighlight lang="vb">Private Function inverse(mat As Variant) As Variant
Dim len_ As Integer: len_ = UBound(mat)
Dim tmp() As Variant
Line 4,236:
Debug.Print
Next i
End Sub</langsyntaxhighlight>{{out}}
<pre> 0,75 0,5 0,25
0,5 1 0,5
Line 4,244:
{{trans|Rexx}}
To run in console mode with cscript.
<langsyntaxhighlight lang="vb">' Gauss-Jordan matrix inversion - VBScript - 22/01/2021
Option Explicit
 
Line 4,332:
c = inverse(b)
show "c", c, "fixed"
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 4,363:
{{libheader|Wren-matrix}}
The above module does in fact use the Gauss-Jordan method for matrix inversion.
<langsyntaxhighlight lang="ecmascript">import "/matrix" for Matrix
import "/fmt" for Fmt
 
Line 4,388:
Fmt.mprint(m.inverse, 9, 6)
System.print()
}</langsyntaxhighlight>
 
{{out}}
Line 4,433:
=={{header|zkl}}==
This uses GSL to invert a matrix via LU decomposition, not Gauss-Jordan.
<langsyntaxhighlight lang="zkl">var [const] GSL=Import.lib("zklGSL"); // libGSL (GNU Scientific Library)
m:=GSL.Matrix(3,3).set(1,2,3, 4,1,6, 7,8,9);
i:=m.invert();
i.format(10,4).println("\n");
(m*i).format(10,4).println();</langsyntaxhighlight>
{{out}}
<pre>
Line 4,448:
-0.0000, 0.0000, 1.0000
</pre>
<langsyntaxhighlight lang="zkl">m:=GSL.Matrix(3,3).set(2,-1,0, -1,2,-1, 0,-1,2);
m.invert().format(10,4).println("\n");</langsyntaxhighlight>
{{out}}
<pre>
10,343

edits

Cookies help us deliver our services. By using our services, you agree to our use of cookies.