Gauss-Jordan matrix inversion: Difference between revisions
m
syntax highlighting fixup automation
SqrtNegInf (talk | contribs) m (→{{header|Raku}}: sync up 'rref') |
Thundergnat (talk | contribs) m (syntax highlighting fixup automation) |
||
Line 10:
{{trans|Nim}}
<
F transformToRref(&mat)
Line 92:
runTest(m1)
runTest(m2)
runTest(m3)</
{{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]].
<
GAUSSJOR CSECT
USING GAUSSJOR,R13 base register
Line 334:
PG DC CL80' ' buffer
REGEQU
END GAUSSJOR </
{{out}}
<pre>
Line 346:
=={{header|ALGOL 60}}==
{{works with|A60}}
<
comment Gauss-Jordan matrix inversion - 22/01/2021;
integer n;
Line 411:
show("c",c)
end
end </
{{out}}
<pre>
Line 433:
=={{header|ALGOL 68}}==
{{Trans|ALGOL 60}}
<
PROC rref = ( REF[,]REAL m )VOID:
BEGIN
Line 490:
c := inverse( b );
show( "c", c )
END</
{{out}}
<pre>
Line 512:
=={{header|C}}==
{{trans|Fortran}}
<
gjinv - Invert a matrix, Gauss-Jordan algorithm
A is destroyed. Returns 1 for a singular matrix.
Line 575:
}
return 0;
} /* end of gjinv */</
Test program:
<
#include <stdio.h>
int main (void)
Line 632:
}
return 0;
} /* end of test program */</
Output is the same as the Fortran example.
=={{header|C sharp|C#}}==
<
using System;
Line 827:
}
}
</syntaxhighlight>
<
using System;
Line 843:
}
}
</syntaxhighlight>
{{out}}<pre>
-0.913043478260869 0.246376811594203 0.0942028985507246 0.413043478260869
Line 852:
=={{header|C++}}==
<
#include <cassert>
#include <iomanip>
Line 990:
print(std::cout, inverse(inv));
return 0;
}</
{{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}}
<
prettyprint sequences ;
Line 1,043:
{ 7 -8 9 1 }
{ 1 -2 1 3 }
} gauss-jordan-invert simple-table.</
{{out}}
<pre>
Line 1,053:
=={{header|Fortran}}==
Note that the Crout algorithm is a more efficient way to invert a matrix.
<
! gjinv - Invert a matrix, Gauss-Jordan algorithm
! A is destroyed.
Line 1,157:
RETURN
END ! of gjinv</
Test program:
{{works with|gfortran|8.3.0}}
<
PROGRAM TINV
IMPLICIT NONE
Line 1,232:
END DO
END ! of test program</
{{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!
<
#include once "rowech.bas"
Line 1,308:
next j
print
next i</
{{out}}
<pre>
Line 1,321:
=={{header|Generic}}==
<
// The Generic Language is a database compiler. This code is compiled into database then executed out of database.
Line 1,993:
}
</syntaxhighlight>
=={{header|Go}}==
{{trans|Kotlin}}
<
import "fmt"
Line 2,081:
b := matrix{{2, -1, 0}, {-1, 2, -1}, {0, -1, 2}}
b.inverse().print("Inverse of B is:\n")
}</
{{out}}
<pre>
Line 2,098:
===Alternative===
{{trans|PowerShell}}
<
import (
Line 2,187:
b := matrix{{2, -1, 0}, {-1, 2, -1}, {0, -1, 2}}
b.inverse().print("Inverse of B is:\n")
}</
{{out}}
<pre>Same output than above</pre>
=={{header|Haskell}}==
<
isSquareMatrix xs = null xs || all ((== (length xs)).length) xs
Line 2,241:
mapM_ print $ inversion a
putStrLn "\ninversion b ="
mapM_ print $ inversion b</
{{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.
<
augmentR_I1=: ,. e.@i.@# NB. augment matrix on the right with its Identity matrix
matrix_invGJ=: # }."1 [: gauss_jordan@augmentR_I1</
'''Usage:'''
<
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</
=={{header|Java}}==
<
import java.util.Random;
Line 2,297:
Matrix.product(m, inv).print();
}
}</
<
public class Matrix {
Line 2,395:
elements[j] = tmp;
}
}</
{{out}}
Line 2,424:
'''Works with gojq, the Go implementation of jq'''
<
# 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] )) ;</
'''The Task'''
<
[ [ 1, 2, 3],
[ 4, 1, 6],
Line 2,532:
;
task</
{{out}}
<pre>
Line 2,572:
'''Built-in''' LAPACK-based linear solver uses partial-pivoted Gauss elimination):
<
@show I / A
@show inv(A)</
'''Native implementation''':
<
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)</
{{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.
<
typealias Matrix = Array<DoubleArray>
Line 2,730:
)
b.inverse().printf("Inverse of B is :\n")
}</
{{out}}
Line 2,748:
=={{header|Lambdatalk}}==
<
{require lib_matrix}
Line 2,759:
[1.4444444444444444,-0.5555555555555556,0.1111111111111111],
[-0.05555555555555555,0.1111111111111111,-0.05555555555555555]]
</syntaxhighlight>
=={{header|Mathematica}} / {{header|Wolfram Language}}==
<
elimmat = RowReduce[Join[a, IdentityMatrix[Length[a]], 2]];
inv = elimmat[[All, -Length[a] ;;]]</
{{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}}==
<
original = M;
[n,~] = size(M);
Line 2,812:
0, -1, 2 ];
GaussInverse(A)</
{{out}}
Line 2,839:
=={{header|Nim}}==
We reuse the algorithm of task https://rosettacode.org/wiki/Reduced_row_echelon_form (version using floats).
<
const Eps = 1e-10
Line 2,945:
runTest(m1)
runTest(m2)
runTest(m3)</
{{out}}
Line 2,984:
=={{header|Perl}}==
Included code from [[Reduced_row_echelon_form#Perl|Reduced row echelon form]] task.
<
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"
}</
{{out}}
<pre>Original Matrix:
Line 3,086:
{{trans|Kotlin}}
uses ToReducedRowEchelonForm() from [[Reduced_row_echelon_form#Phix]]
<!--<
<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>
<!--</
{{out}}
<pre>
Line 3,154:
===alternate===
{{trans|PowerShell}}
<!--<
<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>
<!--</
{{out}}
<pre>
Line 3,264:
=={{header|PowerShell}}==
<syntaxhighlight lang="powershell">
function gauss-jordan-inv([double[][]]$a) {
$n = $a.count
Line 3,317:
show $invb
</syntaxhighlight>
<b>Output:</b>
<pre>
Line 3,345:
Use numpy matrix inversion
<
import numpy as np
from numpy.linalg import inv
Line 3,353:
print(a)
print(ainv)
</syntaxhighlight>
{{out}}
Line 3,369:
Using the matrix library that comes with default Racket installation
<
(require math/matrix
Line 3,382:
(inverse A)
(matrix-inverse A)</
{{out}}
Line 3,395:
Uses bits and pieces from other tasks, [[Reduced_row_echelon_form#Raku|Reduced row echelon form]] primarily.
<syntaxhighlight lang="raku"
^@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 );
}</
{{out}}
Line 3,590:
=={{header|REXX}}==
===version 1===
<
Parse Arg seed nn
If seed='' Then
Line 3,865:
Return bs
Exit: Say arg(1)</
{{out}} Using the defaults for seed and n
<pre>show 1 The given matrix
Line 3,966:
===version 2===
{{trans|PL/I}}
<
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</
{{out|output|text= when using the internal default input:}}
<pre>
Line 4,017:
=={{header|Rust}}==
<
fn main() {
let mut a: Vec<Vec<f64>> = vec![vec![1.0, 2.0, 3.0],
Line 4,131:
}
}
</syntaxhighlight>
{{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}}
<
var I = M.len.of {|i|
Line 4,186:
say gauss_jordan_invert(A).map {
.map { "%6s" % .as_rat }.join(" ")
}.join("\n")</
{{out}}
<pre>
Line 4,197:
=={{header|VBA}}==
{{trans|Phix}}
Uses ToReducedRowEchelonForm() from [[Reduced_row_echelon_form#VBA]]<
Dim len_ As Integer: len_ = UBound(mat)
Dim tmp() As Variant
Line 4,236:
Debug.Print
Next i
End Sub</
<pre> 0,75 0,5 0,25
0,5 1 0,5
Line 4,244:
{{trans|Rexx}}
To run in console mode with cscript.
<
Option Explicit
Line 4,332:
c = inverse(b)
show "c", c, "fixed"
</syntaxhighlight>
{{out}}
<pre>
Line 4,363:
{{libheader|Wren-matrix}}
The above module does in fact use the Gauss-Jordan method for matrix inversion.
<
import "/fmt" for Fmt
Line 4,388:
Fmt.mprint(m.inverse, 9, 6)
System.print()
}</
{{out}}
Line 4,433:
=={{header|zkl}}==
This uses GSL to invert a matrix via LU decomposition, not Gauss-Jordan.
<
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();</
{{out}}
<pre>
Line 4,448:
-0.0000, 0.0000, 1.0000
</pre>
<
m.invert().format(10,4).println("\n");</
{{out}}
<pre>
|