QR decomposition: Difference between revisions
Content added Content deleted
m (→{{header|Phix}}: syntax coloured, improved output formatting a touch) |
Thundergnat (talk | contribs) m (syntax highlighting fixup automation) |
||
Line 98: | Line 98: | ||
=={{header|Ada}}== |
=={{header|Ada}}== |
||
Output matches that of Matlab solution, not tested with other matrices. |
Output matches that of Matlab solution, not tested with other matrices. |
||
<syntaxhighlight lang="ada"> |
|||
<lang Ada> |
|||
with Ada.Text_IO; use Ada.Text_IO; |
with Ada.Text_IO; use Ada.Text_IO; |
||
with Ada.Numerics.Real_Arrays; use Ada.Numerics.Real_Arrays; |
with Ada.Numerics.Real_Arrays; use Ada.Numerics.Real_Arrays; |
||
Line 193: | Line 193: | ||
Put_Line ("Q:"); Show (Q); |
Put_Line ("Q:"); Show (Q); |
||
Put_Line ("R:"); Show (R); |
Put_Line ("R:"); Show (R); |
||
end QR;</ |
end QR;</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre>Q: |
<pre>Q: |
||
Line 206: | Line 206: | ||
=={{header|Axiom}}== |
=={{header|Axiom}}== |
||
The following provides a generic QR decomposition for arbitrary precision floats, double floats and exact calculations: |
The following provides a generic QR decomposition for arbitrary precision floats, double floats and exact calculations: |
||
< |
<syntaxhighlight lang="axiom">)abbrev package TESTP TestPackage |
||
TestPackage(R:Join(Field,RadicalCategory)): with |
TestPackage(R:Join(Field,RadicalCategory)): with |
||
unitVector: NonNegativeInteger -> Vector(R) |
unitVector: NonNegativeInteger -> Vector(R) |
||
Line 260: | Line 260: | ||
for j in 0..n repeat |
for j in 0..n repeat |
||
setColumn!(a,j+1,x^j) |
setColumn!(a,j+1,x^j) |
||
lsqr(a,y)</ |
lsqr(a,y)</syntaxhighlight> |
||
This can be called using: |
This can be called using: |
||
< |
<syntaxhighlight lang="axiom">m := matrix [[12, -51, 4], [6, 167, -68], [-4, 24, -41]]; |
||
qr m |
qr m |
||
x := vector [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]; |
x := vector [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]; |
||
y := vector [1, 6, 17, 34, 57, 86, 121, 162, 209, 262, 321]; |
y := vector [1, 6, 17, 34, 57, 86, 121, 162, 209, 262, 321]; |
||
polyfit(x, y, 2)</ |
polyfit(x, y, 2)</syntaxhighlight> |
||
With output in exact form: |
With output in exact form: |
||
< |
<syntaxhighlight lang="axiom">qr m |
||
+ 6 69 58 + |
+ 6 69 58 + |
||
Line 287: | Line 287: | ||
[1,2,3] |
[1,2,3] |
||
Type: Vector(AlgebraicNumber)</ |
Type: Vector(AlgebraicNumber)</syntaxhighlight> |
||
The calculations are comparable to those from the default QR decomposition in R. |
The calculations are comparable to those from the default QR decomposition in R. |
||
Line 293: | Line 293: | ||
{{works with|BBC BASIC for Windows}} |
{{works with|BBC BASIC for Windows}} |
||
Makes heavy use of BBC BASIC's matrix arithmetic. |
Makes heavy use of BBC BASIC's matrix arithmetic. |
||
< |
<syntaxhighlight lang="bbcbasic"> *FLOAT 64 |
||
@% = &2040A |
@% = &2040A |
||
INSTALL @lib$+"ARRAYLIB" |
INSTALL @lib$+"ARRAYLIB" |
||
Line 389: | Line 389: | ||
REM Create the Householder matrix H() = I - 2/vt()v() v()vt(): |
REM Create the Householder matrix H() = I - 2/vt()v() v()vt(): |
||
vvt() *= 2 / d(0) : H() = I() - vvt() |
vvt() *= 2 / d(0) : H() = I() - vvt() |
||
ENDPROC</ |
ENDPROC</syntaxhighlight> |
||
'''Output:''' |
'''Output:''' |
||
<pre> |
<pre> |
||
Line 406: | Line 406: | ||
=={{header|C}}== |
=={{header|C}}== |
||
< |
<syntaxhighlight lang="c">#include <stdio.h> |
||
#include <stdlib.h> |
#include <stdlib.h> |
||
#include <math.h> |
#include <math.h> |
||
Line 597: | Line 597: | ||
matrix_delete(m); |
matrix_delete(m); |
||
return 0; |
return 0; |
||
}</ |
}</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre> |
<pre> |
||
Line 626: | Line 626: | ||
{{libheader|Math.Net}} |
{{libheader|Math.Net}} |
||
< |
<syntaxhighlight lang="csharp">using System; |
||
using MathNet.Numerics.LinearAlgebra; |
using MathNet.Numerics.LinearAlgebra; |
||
using MathNet.Numerics.LinearAlgebra.Double; |
using MathNet.Numerics.LinearAlgebra.Double; |
||
Line 652: | Line 652: | ||
Console.WriteLine(qr.R); |
Console.WriteLine(qr.R); |
||
} |
} |
||
}</ |
}</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
Line 677: | Line 677: | ||
=={{header|C++}}== |
=={{header|C++}}== |
||
< |
<syntaxhighlight lang="cpp">/* |
||
* g++ -O3 -Wall --std=c++11 qr_standalone.cpp -o qr_standalone |
* g++ -O3 -Wall --std=c++11 qr_standalone.cpp -o qr_standalone |
||
*/ |
*/ |
||
Line 1,072: | Line 1,072: | ||
return EXIT_SUCCESS; |
return EXIT_SUCCESS; |
||
} |
} |
||
</syntaxhighlight> |
|||
</lang> |
|||
{{out}} |
{{out}} |
||
<pre> |
<pre> |
||
Line 1,108: | Line 1,108: | ||
Helper functions: |
Helper functions: |
||
< |
<syntaxhighlight lang="lisp">(defun sign (x) |
||
(if (zerop x) |
(if (zerop x) |
||
x |
x |
||
Line 1,162: | Line 1,162: | ||
C)) |
C)) |
||
</syntaxhighlight> |
|||
</lang> |
|||
Main routines: |
Main routines: |
||
< |
<syntaxhighlight lang="lisp"> |
||
(defun make-householder (a) |
(defun make-householder (a) |
||
(let* ((m (car (array-dimensions a))) |
(let* ((m (car (array-dimensions a))) |
||
Line 1,200: | Line 1,200: | ||
;; Return Q and R. |
;; Return Q and R. |
||
(values Q A))) |
(values Q A))) |
||
</syntaxhighlight> |
|||
</lang> |
|||
Example 1: |
Example 1: |
||
< |
<syntaxhighlight lang="lisp">(qr #2A((12 -51 4) (6 167 -68) (-4 24 -41))) |
||
#2A((-0.85 0.39 0.33) |
#2A((-0.85 0.39 0.33) |
||
Line 1,212: | Line 1,212: | ||
#2A((-14.0 -21.0 14.0) |
#2A((-14.0 -21.0 14.0) |
||
( 0.0 -175.0 70.0) |
( 0.0 -175.0 70.0) |
||
( 0.0 0.0 -35.0))</ |
( 0.0 0.0 -35.0))</syntaxhighlight> |
||
Example 2, [[Polynomial regression]]: |
Example 2, [[Polynomial regression]]: |
||
< |
<syntaxhighlight lang="lisp">(defun polyfit (x y n) |
||
(let* ((m (cadr (array-dimensions x))) |
(let* ((m (cadr (array-dimensions x))) |
||
(A (make-array `(,m ,(+ n 1)) :initial-element 0))) |
(A (make-array `(,m ,(+ n 1)) :initial-element 0))) |
||
Line 1,244: | Line 1,244: | ||
(aref x j 0)))) |
(aref x j 0)))) |
||
(aref R k k)))) |
(aref R k k)))) |
||
x))</ |
x))</syntaxhighlight> |
||
< |
<syntaxhighlight lang="lisp">;; Finally use the data: |
||
(let ((x #2A((0 1 2 3 4 5 6 7 8 9 10))) |
(let ((x #2A((0 1 2 3 4 5 6 7 8 9 10))) |
||
(y #2A((1 6 17 34 57 86 121 162 209 262 321)))) |
(y #2A((1 6 17 34 57 86 121 162 209 262 321)))) |
||
(polyfit x y 2)) |
(polyfit x y 2)) |
||
#2A((0.999999966345088) (2.000000015144699) (2.99999999879804))</ |
#2A((0.999999966345088) (2.000000015144699) (2.99999999879804))</syntaxhighlight> |
||
=={{header|D}}== |
=={{header|D}}== |
||
{{trans|Common Lisp}} |
{{trans|Common Lisp}} |
||
Uses the functions copied from [[Element-wise_operations]], [[Matrix multiplication]], and [[Matrix transposition]]. |
Uses the functions copied from [[Element-wise_operations]], [[Matrix multiplication]], and [[Matrix transposition]]. |
||
< |
<syntaxhighlight lang="d">import std.stdio, std.math, std.algorithm, std.traits, |
||
std.typecons, std.numeric, std.range, std.conv; |
std.typecons, std.numeric, std.range, std.conv; |
||
Line 1,457: | Line 1,457: | ||
immutable y = [[1.0, 6, 17, 34, 57, 86, 121, 162, 209, 262, 321]]; |
immutable y = [[1.0, 6, 17, 34, 57, 86, 121, 162, 209, 262, 321]]; |
||
polyFit(x, y, 2).writeln; |
polyFit(x, y, 2).writeln; |
||
}</ |
}</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre>[[-0.857, 0.394, 0.331], |
<pre>[[-0.857, 0.394, 0.331], |
||
Line 1,470: | Line 1,470: | ||
=={{header|F_Sharp|F#}}== |
=={{header|F_Sharp|F#}}== |
||
< |
<syntaxhighlight lang="fsharp"> |
||
// QR decomposition. Nigel Galloway: January 11th., 2022 |
// QR decomposition. Nigel Galloway: January 11th., 2022 |
||
let n=[[12.0;-51.0;4.0];[6.0;167.0;-68.0];[-4.0;24.0;-41.0]]|>MathNet.Numerics.LinearAlgebra.MatrixExtensions.matrix |
let n=[[12.0;-51.0;4.0];[6.0;167.0;-68.0];[-4.0;24.0;-41.0]]|>MathNet.Numerics.LinearAlgebra.MatrixExtensions.matrix |
||
let g=n|>MathNet.Numerics.LinearAlgebra.Matrix.qr |
let g=n|>MathNet.Numerics.LinearAlgebra.Matrix.qr |
||
printfn $"Matrix\n------\n%A{n}\nQ\n-\n%A{g.Q}\nR\n-\n%A{g.R}" |
printfn $"Matrix\n------\n%A{n}\nQ\n-\n%A{g.Q}\nR\n-\n%A{g.R}" |
||
</syntaxhighlight> |
|||
</lang> |
|||
{{out}} |
{{out}} |
||
<pre> |
<pre> |
||
Line 1,505: | Line 1,505: | ||
See the documentation for the [http://www.netlib.org/lapack/lapack-3.1.1/html/dgeqrf.f.html DGEQRF] and [http://www.netlib.org/lapack/lapack-3.1.1/html/dorgqr.f.html DORGQR] routines. Here the example matrix is the magic square from Albrecht Dürer's ''[https://en.wikipedia.org/wiki/Melencolia_I Melencolia I]''. |
See the documentation for the [http://www.netlib.org/lapack/lapack-3.1.1/html/dgeqrf.f.html DGEQRF] and [http://www.netlib.org/lapack/lapack-3.1.1/html/dorgqr.f.html DORGQR] routines. Here the example matrix is the magic square from Albrecht Dürer's ''[https://en.wikipedia.org/wiki/Melencolia_I Melencolia I]''. |
||
< |
<syntaxhighlight lang="fortran">program qrtask |
||
implicit none |
implicit none |
||
integer, parameter :: n = 4 |
integer, parameter :: n = 4 |
||
Line 1,547: | Line 1,547: | ||
end do |
end do |
||
end subroutine |
end subroutine |
||
end program</ |
end program</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
Line 1,578: | Line 1,578: | ||
=={{header|Futhark}}== |
=={{header|Futhark}}== |
||
<syntaxhighlight lang="futhark"> |
|||
<lang Futhark> |
|||
import "lib/github.com/diku-dk/linalg/linalg" |
import "lib/github.com/diku-dk/linalg/linalg" |
||
Line 1,609: | Line 1,609: | ||
entry main = qr [[12.0, -51.0, 4.0],[6.0, 167.0, -68.0],[-4.0, 24.0, -41.0]] |
entry main = qr [[12.0, -51.0, 4.0],[6.0, 167.0, -68.0],[-4.0, 24.0, -41.0]] |
||
</syntaxhighlight> |
|||
</lang> |
|||
{{out}} |
{{out}} |
||
<pre> |
<pre> |
||
Line 1,621: | Line 1,621: | ||
{{trans|Common Lisp}} |
{{trans|Common Lisp}} |
||
A fairly close port of the Common Lisp solution, this solution uses the [http://github.com/skelterjohn/go.matrix go.matrix library] for supporting functions. Note though, that go.matrix has QR decomposition, as shown in the [[Polynomial_regression#Go|Go solution]] to Polynomial regression. The solution there is coded more directly than by following the CL example here. Similarly, examination of the go.matrix QR source shows that it computes the decomposition more directly. |
A fairly close port of the Common Lisp solution, this solution uses the [http://github.com/skelterjohn/go.matrix go.matrix library] for supporting functions. Note though, that go.matrix has QR decomposition, as shown in the [[Polynomial_regression#Go|Go solution]] to Polynomial regression. The solution there is coded more directly than by following the CL example here. Similarly, examination of the go.matrix QR source shows that it computes the decomposition more directly. |
||
< |
<syntaxhighlight lang="go">package main |
||
import ( |
import ( |
||
Line 1,727: | Line 1,727: | ||
} |
} |
||
return x |
return x |
||
}</ |
}</syntaxhighlight> |
||
Output: |
Output: |
||
<pre> |
<pre> |
||
Line 1,746: | Line 1,746: | ||
===Library QR, gonum/matrix=== |
===Library QR, gonum/matrix=== |
||
< |
<syntaxhighlight lang="go">package main |
||
import ( |
import ( |
||
Line 1,789: | Line 1,789: | ||
} |
} |
||
return x |
return x |
||
}</ |
}</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre> |
<pre> |
||
Line 1,807: | Line 1,807: | ||
=={{header|Haskell}}== |
=={{header|Haskell}}== |
||
Square matrices only; decompose A and solve Rx = q by back substitution |
Square matrices only; decompose A and solve Rx = q by back substitution |
||
< |
<syntaxhighlight lang="haskell"> |
||
import Data.List |
import Data.List |
||
import Text.Printf (printf) |
import Text.Printf (printf) |
||
Line 1,888: | Line 1,888: | ||
putStrLn ("q: \n" ++ show q) >> |
putStrLn ("q: \n" ++ show q) >> |
||
putStrLn ("x: \n" ++ show (backSubstitution (reverse (map reverse mR)) (reverse q) [])) |
putStrLn ("x: \n" ++ show (backSubstitution (reverse (map reverse mR)) (reverse q) [])) |
||
</syntaxhighlight> |
|||
</lang> |
|||
{{out}} |
{{out}} |
||
<pre> |
<pre> |
||
Line 1,906: | Line 1,906: | ||
===QR decomposition with Numeric.LinearAlgebra=== |
===QR decomposition with Numeric.LinearAlgebra=== |
||
< |
<syntaxhighlight lang="haskell">import Numeric.LinearAlgebra |
||
a :: Matrix R |
a :: Matrix R |
||
Line 1,916: | Line 1,916: | ||
main = do |
main = do |
||
print $ qr a |
print $ qr a |
||
</syntaxhighlight> |
|||
</lang> |
|||
{{out}} |
{{out}} |
||
<pre>((3><3) |
<pre>((3><3) |
||
Line 1,929: | Line 1,929: | ||
=={{header|J}}== |
=={{header|J}}== |
||
'''Solution''' (built-in):< |
'''Solution''' (built-in):<syntaxhighlight lang="j"> QR =: 128!:0</syntaxhighlight> |
||
'''Solution''' (custom implementation): < |
'''Solution''' (custom implementation): <syntaxhighlight lang="j"> mp=: +/ . * NB. matrix product |
||
h =: +@|: NB. conjugate transpose |
h =: +@|: NB. conjugate transpose |
||
Line 1,945: | Line 1,945: | ||
(Q0,.Q1);(R0,.T),(-n){."1 R1 |
(Q0,.Q1);(R0,.T),(-n){."1 R1 |
||
end. |
end. |
||
)</ |
)</syntaxhighlight> |
||
'''Example''': < |
'''Example''': <syntaxhighlight lang="j"> QR 12 _51 4,6 167 _68,:_4 24 _41 |
||
+-----------------------------+----------+ |
+-----------------------------+----------+ |
||
| 0.857143 _0.394286 _0.331429|14 21 _14| |
| 0.857143 _0.394286 _0.331429|14 21 _14| |
||
| 0.428571 0.902857 0.0342857| 0 175 _70| |
| 0.428571 0.902857 0.0342857| 0 175 _70| |
||
|_0.285714 0.171429 _0.942857| 0 0 35| |
|_0.285714 0.171429 _0.942857| 0 0 35| |
||
+-----------------------------+----------+</ |
+-----------------------------+----------+</syntaxhighlight> |
||
'''Example''' (polynomial fitting using QR reduction):< |
'''Example''' (polynomial fitting using QR reduction):<syntaxhighlight lang="j"> X=:i.# Y=:1 6 17 34 57 86 121 162 209 262 321 |
||
'Q R'=: QR X ^/ i.3 |
'Q R'=: QR X ^/ i.3 |
||
R %.~(|:Q)+/ .* Y |
R %.~(|:Q)+/ .* Y |
||
1 2 3</ |
1 2 3</syntaxhighlight> |
||
'''Notes''':J offers a built-in QR decomposition function, <tt>128!:0</tt>. If J did not offer this function as a built-in, it could be written in J along the lines of the second version, which is covered in [[j:Essays/QR Decomposition|an essay on the J wiki]]. |
'''Notes''':J offers a built-in QR decomposition function, <tt>128!:0</tt>. If J did not offer this function as a built-in, it could be written in J along the lines of the second version, which is covered in [[j:Essays/QR Decomposition|an essay on the J wiki]]. |
||
Line 1,964: | Line 1,964: | ||
Using the [https://math.nist.gov/javanumerics/jama/ JAMA] library. Compile with: '''javac -cp Jama-1.0.3.jar Decompose.java'''. |
Using the [https://math.nist.gov/javanumerics/jama/ JAMA] library. Compile with: '''javac -cp Jama-1.0.3.jar Decompose.java'''. |
||
< |
<syntaxhighlight lang="java">import Jama.Matrix; |
||
import Jama.QRDecomposition; |
import Jama.QRDecomposition; |
||
Line 1,979: | Line 1,979: | ||
qr.getR().print(10, 4); |
qr.getR().print(10, 4); |
||
} |
} |
||
}</ |
}</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
Line 1,995: | Line 1,995: | ||
Using the [https://dst.lbl.gov/ACSSoftware/colt/ Colt] library. Compile with: '''javac -cp colt.jar Decompose.java'''. |
Using the [https://dst.lbl.gov/ACSSoftware/colt/ Colt] library. Compile with: '''javac -cp colt.jar Decompose.java'''. |
||
< |
<syntaxhighlight lang="java">import cern.colt.matrix.impl.DenseDoubleMatrix2D; |
||
import cern.colt.matrix.linalg.QRDecomposition; |
import cern.colt.matrix.linalg.QRDecomposition; |
||
Line 2,010: | Line 2,010: | ||
System.out.println(qr.getR()); |
System.out.println(qr.getR()); |
||
} |
} |
||
}</ |
}</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
Line 2,030: | Line 2,030: | ||
Compile with: '''javac -cp commons-math3-3.6.1.jar Decompose.java'''. |
Compile with: '''javac -cp commons-math3-3.6.1.jar Decompose.java'''. |
||
< |
<syntaxhighlight lang="java">import java.util.Locale; |
||
import org.apache.commons.math3.linear.Array2DRowRealMatrix; |
import org.apache.commons.math3.linear.Array2DRowRealMatrix; |
||
Line 2,059: | Line 2,059: | ||
} |
} |
||
} |
} |
||
}</ |
}</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
Line 2,075: | Line 2,075: | ||
Using the [http://la4j.org/ la4j] library. Compile with: '''javac -cp la4j-0.6.0.jar Decompose.java'''. |
Using the [http://la4j.org/ la4j] library. Compile with: '''javac -cp la4j-0.6.0.jar Decompose.java'''. |
||
< |
<syntaxhighlight lang="java">import org.la4j.Matrix; |
||
import org.la4j.decomposition.QRDecompositor; |
import org.la4j.decomposition.QRDecompositor; |
||
Line 2,090: | Line 2,090: | ||
System.out.println(qr[1]); |
System.out.println(qr[1]); |
||
} |
} |
||
}</ |
}</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
Line 2,104: | Line 2,104: | ||
=={{header|Julia}}== |
=={{header|Julia}}== |
||
Built-in function |
Built-in function |
||
< |
<syntaxhighlight lang="julia">Q, R = qr([12 -51 4; 6 167 -68; -4 24 -41])</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre> |
<pre> |
||
Line 2,121: | Line 2,121: | ||
=={{header|Maple}}== |
=={{header|Maple}}== |
||
< |
<syntaxhighlight lang="maple">with(LinearAlgebra): |
||
A:=<12,-51,4;6,167,-68;-4,24,-41>: |
A:=<12,-51,4;6,167,-68;-4,24,-41>: |
||
Q,R:=QRDecomposition(A): |
Q,R:=QRDecomposition(A): |
||
Q; |
Q; |
||
R;</ |
R;</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
Line 2,149: | Line 2,149: | ||
=={{header|Mathematica}}/{{header|Wolfram Language}}== |
=={{header|Mathematica}}/{{header|Wolfram Language}}== |
||
< |
<syntaxhighlight lang="mathematica">{q,r}=QRDecomposition[{{12, -51, 4}, {6, 167, -68}, {-4, 24, -41}}]; |
||
q//MatrixForm |
q//MatrixForm |
||
Line 2,159: | Line 2,159: | ||
-> 14 21 -14 |
-> 14 21 -14 |
||
0 175 -70 |
0 175 -70 |
||
0 0 35</ |
0 0 35</syntaxhighlight> |
||
=={{header|MATLAB}} / {{header|Octave}}== |
=={{header|MATLAB}} / {{header|Octave}}== |
||
< |
<syntaxhighlight lang="matlab"> A = [12 -51 4 |
||
6 167 -68 |
6 167 -68 |
||
-4 24 -41]; |
-4 24 -41]; |
||
[Q,R]=qr(A) </ |
[Q,R]=qr(A) </syntaxhighlight> |
||
Output: |
Output: |
||
<pre>Q = |
<pre>Q = |
||
Line 2,180: | Line 2,180: | ||
=={{header|Maxima}}== |
=={{header|Maxima}}== |
||
< |
<syntaxhighlight lang="maxima">load(lapack)$ /* This may hang up in wxMaxima, if this happens, use xMaxima or plain Maxima in a terminal */ |
||
a: matrix([12, -51, 4], |
a: matrix([12, -51, 4], |
||
Line 2,191: | Line 2,191: | ||
4.2632564145606011E-14 |
4.2632564145606011E-14 |
||
/* Note: the lapack package is a lisp translation of the fortran lapack library */</ |
/* Note: the lapack package is a lisp translation of the fortran lapack library */</syntaxhighlight> |
||
For an exact or arbitrary precision solution:< |
For an exact or arbitrary precision solution:<syntaxhighlight lang="maxima">load("linearalgebra")$ |
||
load("eigen")$ |
load("eigen")$ |
||
unitVector(n) := ematrix(n,1,1,1,1); |
unitVector(n) := ematrix(n,1,1,1,1); |
||
Line 2,235: | Line 2,235: | ||
a : genmatrix(lambda([i,j], if j=1 then 1.0b0 else bfloat(x[i,1]^(j-1))), |
a : genmatrix(lambda([i,j], if j=1 then 1.0b0 else bfloat(x[i,1]^(j-1))), |
||
length(x),n+1), |
length(x),n+1), |
||
lsqr(a,y));</ |
lsqr(a,y));</syntaxhighlight>Then we have the examples:<syntaxhighlight lang="maxima">(%i) [q,r] : qr(a); |
||
[ 6 69 58 ] |
[ 6 69 58 ] |
||
Line 2,263: | Line 2,263: | ||
(%o) [ 2.00000000000000000000000000002b0 ] |
(%o) [ 2.00000000000000000000000000002b0 ] |
||
[ ] |
[ ] |
||
[ 3.0b0 ]</ |
[ 3.0b0 ]</syntaxhighlight> |
||
=={{header|Nim}}== |
=={{header|Nim}}== |
||
Line 2,269: | Line 2,269: | ||
{{libheader|arraymancer}} |
{{libheader|arraymancer}} |
||
The library “arraymancer” provides a function “qr” to get the QR decomposition. Using the Tensor type of “arraymancer” we propose here an implementation of this decomposition adapted from the Python version. |
The library “arraymancer” provides a function “qr” to get the QR decomposition. Using the Tensor type of “arraymancer” we propose here an implementation of this decomposition adapted from the Python version. |
||
< |
<syntaxhighlight lang="nim">import math, strformat, strutils |
||
import arraymancer |
import arraymancer |
||
Line 2,352: | Line 2,352: | ||
let y = [1, 6, 17, 34, 57, 86, 121, 162, 209, 262, 321].toTensor.astype(float) |
let y = [1, 6, 17, 34, 57, 86, 121, 162, 209, 262, 321].toTensor.astype(float) |
||
echo "polyfit:" |
echo "polyfit:" |
||
printVector polyfit(x, y, 2)</ |
printVector polyfit(x, y, 2)</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
Line 2,369: | Line 2,369: | ||
=={{header|PARI/GP}}== |
=={{header|PARI/GP}}== |
||
{{works with|PARI/GP|2.6.0 and above}} |
{{works with|PARI/GP|2.6.0 and above}} |
||
<lang |
<syntaxhighlight lang="parigp">matqr(M)</syntaxhighlight> |
||
=={{header|Perl}}== |
=={{header|Perl}}== |
||
Letting the <code>PDL</code> module do all the work. |
Letting the <code>PDL</code> module do all the work. |
||
< |
<syntaxhighlight lang="perl">use strict; |
||
use warnings; |
use warnings; |
||
Line 2,388: | Line 2,388: | ||
my ($q, $r) = mqr($a); |
my ($q, $r) = mqr($a); |
||
print $q, $r, $q x $r;</ |
print $q, $r, $q x $r;</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre>[ |
<pre>[ |
||
Line 2,415: | Line 2,415: | ||
using matrix_mul() from [[Matrix_multiplication#Phix]] |
using matrix_mul() from [[Matrix_multiplication#Phix]] |
||
and matrix_transpose() from [[Matrix_transposition#Phix]] |
and matrix_transpose() from [[Matrix_transposition#Phix]] |
||
<!--< |
<!--<syntaxhighlight lang="phix">(phixonline)--> |
||
<span style="color: #000080;font-style:italic;">-- demo/rosettacode/QRdecomposition.exw</span> |
<span style="color: #000080;font-style:italic;">-- demo/rosettacode/QRdecomposition.exw</span> |
||
<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> |
||
Line 2,563: | Line 2,563: | ||
<span style="color: #008080;">end</span> <span style="color: #008080;">procedure</span> |
<span style="color: #008080;">end</span> <span style="color: #008080;">procedure</span> |
||
<span style="color: #000000;">least_squares</span><span style="color: #0000FF;">()</span> |
<span style="color: #000000;">least_squares</span><span style="color: #0000FF;">()</span> |
||
<!--</ |
<!--</syntaxhighlight>--> |
||
{{out}} |
{{out}} |
||
<pre> |
<pre> |
||
Line 2,591: | Line 2,591: | ||
=={{header|PowerShell}}== |
=={{header|PowerShell}}== |
||
<syntaxhighlight lang="powershell"> |
|||
<lang PowerShell> |
|||
function qr([double[][]]$A) { |
function qr([double[][]]$A) { |
||
$m,$n = $A.count, $A[0].count |
$m,$n = $A.count, $A[0].count |
||
Line 2,678: | Line 2,678: | ||
"X^2 X constant" |
"X^2 X constant" |
||
"$(polyfit $x $y 2)" |
"$(polyfit $x $y 2)" |
||
</syntaxhighlight> |
|||
</lang> |
|||
{{out}} |
{{out}} |
||
<pre> |
<pre> |
||
Line 2,697: | Line 2,697: | ||
{{libheader|NumPy}} |
{{libheader|NumPy}} |
||
Numpy has a qr function but here is a reimplementation to show construction and use of the Householder reflections. |
Numpy has a qr function but here is a reimplementation to show construction and use of the Householder reflections. |
||
< |
<syntaxhighlight lang="python">#!/usr/bin/env python3 |
||
import numpy as np |
import numpy as np |
||
Line 2,741: | Line 2,741: | ||
y = np.array((1, 6, 17, 34, 57, 86, 121, 162, 209, 262, 321)) |
y = np.array((1, 6, 17, 34, 57, 86, 121, 162, 209, 262, 321)) |
||
print('\npolyfit:\n', polyfit(x, y, 2))</ |
print('\npolyfit:\n', polyfit(x, y, 2))</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre> |
<pre> |
||
Line 2,758: | Line 2,758: | ||
=={{header|R}}== |
=={{header|R}}== |
||
< |
<syntaxhighlight lang="r"># R has QR decomposition built-in (using LAPACK or LINPACK) |
||
a <- matrix(c(12, -51, 4, 6, 167, -68, -4, 24, -41), nrow=3, ncol=3, byrow=T) |
a <- matrix(c(12, -51, 4, 6, 167, -68, -4, 24, -41), nrow=3, ncol=3, byrow=T) |
||
Line 2,780: | Line 2,780: | ||
xx <- x*x |
xx <- x*x |
||
m <- lm(y ~ x + xx) |
m <- lm(y ~ x + xx) |
||
coef(m)</ |
coef(m)</syntaxhighlight> |
||
=={{header|Racket}}== |
=={{header|Racket}}== |
||
Racket has QR-decomposition builtin: |
Racket has QR-decomposition builtin: |
||
< |
<syntaxhighlight lang="racket"> |
||
> (require math) |
> (require math) |
||
> (matrix-qr (matrix [[12 -51 4] |
> (matrix-qr (matrix [[12 -51 4] |
||
Line 2,792: | Line 2,792: | ||
(array #[#[6/7 -69/175 -58/175] #[3/7 158/175 6/175] #[-2/7 6/35 -33/35]]) |
(array #[#[6/7 -69/175 -58/175] #[3/7 158/175 6/175] #[-2/7 6/35 -33/35]]) |
||
(array #[#[14 21 -14] #[0 175 -70] #[0 0 35]]) |
(array #[#[14 21 -14] #[0 175 -70] #[0 0 35]]) |
||
</syntaxhighlight> |
|||
</lang> |
|||
The builtin QR-decomposition uses the Gram-Schmidt algorithm. |
The builtin QR-decomposition uses the Gram-Schmidt algorithm. |
||
Here is an implementation of the Householder method: |
Here is an implementation of the Householder method: |
||
< |
<syntaxhighlight lang="racket"> |
||
#lang racket |
#lang racket |
||
(require math/matrix math/array) |
(require math/matrix math/array) |
||
Line 2,827: | Line 2,827: | ||
[ 6 167 -68] |
[ 6 167 -68] |
||
[-4 24 -41]])) |
[-4 24 -41]])) |
||
</syntaxhighlight> |
|||
</lang> |
|||
Output: |
Output: |
||
< |
<syntaxhighlight lang="racket"> |
||
(array #[#[6/7 69/175 -58/175] |
(array #[#[6/7 69/175 -58/175] |
||
#[3/7 -158/175 6/175] |
#[3/7 -158/175 6/175] |
||
Line 2,836: | Line 2,836: | ||
#[0 -175 70] |
#[0 -175 70] |
||
#[0 0 35]]) |
#[0 0 35]]) |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|Raku}}== |
=={{header|Raku}}== |
||
(formerly Perl 6) |
(formerly Perl 6) |
||
{{Works with|rakudo|2018.06}} |
{{Works with|rakudo|2018.06}} |
||
<lang |
<syntaxhighlight lang="raku" line># sub householder translated from https://codereview.stackexchange.com/questions/120978/householder-transformation |
||
use v6; |
use v6; |
||
Line 3,020: | Line 3,020: | ||
"\n", |
"\n", |
||
@coef.fmt("%12.6f"); |
@coef.fmt("%12.6f"); |
||
}</ |
}</syntaxhighlight> |
||
output: |
output: |
||
Line 3,062: | Line 3,062: | ||
This function applies the Gram Schmidt algorithm. Q is printed in the console, R can be printed or visualized. |
This function applies the Gram Schmidt algorithm. Q is printed in the console, R can be printed or visualized. |
||
< |
<syntaxhighlight lang="rascal">import util::Math; |
||
import Prelude; |
import Prelude; |
||
import vis::Figure; |
import vis::Figure; |
||
Line 3,154: | Line 3,154: | ||
<1.0,0.0,-51.0>, <1.0,1.0,167.0>, <1.0,2.0,24.0>, |
<1.0,0.0,-51.0>, <1.0,1.0,167.0>, <1.0,2.0,24.0>, |
||
<2.0,0.0,4.0>, <2.0,1.0,-68.0>, <2.0,2.0,-41.0> |
<2.0,0.0,4.0>, <2.0,1.0,-68.0>, <2.0,2.0,-41.0> |
||
};</ |
};</syntaxhighlight> |
||
Example using visualization |
Example using visualization |
||
Line 3,174: | Line 3,174: | ||
=={{header|SAS}}== |
=={{header|SAS}}== |
||
< |
<syntaxhighlight lang="sas">/* See http://support.sas.com/documentation/cdl/en/imlug/63541/HTML/default/viewer.htm#imlug_langref_sect229.htm */ |
||
proc iml; |
proc iml; |
||
Line 3,204: | Line 3,204: | ||
0 -175 70 |
0 -175 70 |
||
0 0 35 |
0 0 35 |
||
*/</ |
*/</syntaxhighlight> |
||
=={{header|Scala}}== |
=={{header|Scala}}== |
||
{{Out}}Best seen running in your browser [https://scastie.scala-lang.org/NMueO16uQl6oivliBKZHew Scastie (remote JVM)]. |
{{Out}}Best seen running in your browser [https://scastie.scala-lang.org/NMueO16uQl6oivliBKZHew Scastie (remote JVM)]. |
||
< |
<syntaxhighlight lang="scala">import java.io.{PrintWriter, StringWriter} |
||
import Jama.{Matrix, QRDecomposition} |
import Jama.{Matrix, QRDecomposition} |
||
Line 3,229: | Line 3,229: | ||
print(toString(d.getR)) |
print(toString(d.getR)) |
||
}</ |
}</syntaxhighlight> |
||
=={{header|SequenceL}}== |
=={{header|SequenceL}}== |
||
{{trans|Go}} |
{{trans|Go}} |
||
< |
<syntaxhighlight lang="sequencel">import <Utilities/Math.sl>; |
||
import <Utilities/Sequence.sl>; |
import <Utilities/Sequence.sl>; |
||
import <Utilities/Conversion.sl>; |
import <Utilities/Conversion.sl>; |
||
Line 3,321: | Line 3,321: | ||
j within 1 ... n; |
j within 1 ... n; |
||
mm(A(2), B(2))[i,j] := sum( A[i] * transpose(B)[j] );</ |
mm(A(2), B(2))[i,j] := sum( A[i] * transpose(B)[j] );</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
Line 3,345: | Line 3,345: | ||
{{trans|Axiom}} |
{{trans|Axiom}} |
||
We first define a signature for a radical category joined with a field. We then define a functor with (a) structures to define operators and functions for Array and Array2, and (b) functions for the QR decomposition: |
We first define a signature for a radical category joined with a field. We then define a functor with (a) structures to define operators and functions for Array and Array2, and (b) functions for the QR decomposition: |
||
< |
<syntaxhighlight lang="sml">signature RADCATFIELD = sig |
||
type real |
type real |
||
val zero : real |
val zero : real |
||
Line 3,470: | Line 3,470: | ||
lsqr(a,y) |
lsqr(a,y) |
||
end |
end |
||
end</ |
end</syntaxhighlight> |
||
We can then show the examples:< |
We can then show the examples:<syntaxhighlight lang="sml">structure RealRadicalCategoryField : RADCATFIELD = struct |
||
open Real |
open Real |
||
val one = 1.0 |
val one = 1.0 |
||
Line 3,503: | Line 3,503: | ||
(* output *) |
(* output *) |
||
val it = [|1.0,2.0,3.0|] : real array</ |
val it = [|1.0,2.0,3.0|] : real array</syntaxhighlight> |
||
=={{header|Stata}}== |
=={{header|Stata}}== |
||
See [http://www.stata.com/help.cgi?mf_qrd QR decomposition] in Stata help. |
See [http://www.stata.com/help.cgi?mf_qrd QR decomposition] in Stata help. |
||
< |
<syntaxhighlight lang="stata">mata |
||
: qrd(a=(12,-51,4\6,167,-68\-4,24,-41),q=.,r=.) |
: qrd(a=(12,-51,4\6,167,-68\-4,24,-41),q=.,r=.) |
||
Line 3,533: | Line 3,533: | ||
2 | 0 -175 70 | |
2 | 0 -175 70 | |
||
3 | 0 0 -35 | |
3 | 0 0 -35 | |
||
+----------------------+</ |
+----------------------+</syntaxhighlight> |
||
=={{header|Tcl}}== |
=={{header|Tcl}}== |
||
Assuming the presence of the Tcl solutions to these tasks: [[Element-wise operations]], [[Matrix multiplication]], [[Matrix transposition]] |
Assuming the presence of the Tcl solutions to these tasks: [[Element-wise operations]], [[Matrix multiplication]], [[Matrix transposition]] |
||
{{trans|Common Lisp}} |
{{trans|Common Lisp}} |
||
< |
<syntaxhighlight lang="tcl">package require Tcl 8.5 |
||
namespace path {::tcl::mathfunc ::tcl::mathop} |
namespace path {::tcl::mathfunc ::tcl::mathop} |
||
proc sign x {expr {$x == 0 ? 0 : $x < 0 ? -1 : 1}} |
proc sign x {expr {$x == 0 ? 0 : $x < 0 ? -1 : 1}} |
||
Line 3,595: | Line 3,595: | ||
} |
} |
||
return [list $Q $A] |
return [list $Q $A] |
||
}</ |
}</syntaxhighlight> |
||
Demonstrating: |
Demonstrating: |
||
< |
<syntaxhighlight lang="tcl">set demo [qrDecompose {{12 -51 4} {6 167 -68} {-4 24 -41}}] |
||
puts "==Q==" |
puts "==Q==" |
||
print_matrix [lindex $demo 0] "%f" |
print_matrix [lindex $demo 0] "%f" |
||
puts "==R==" |
puts "==R==" |
||
print_matrix [lindex $demo 1] "%.1f"</ |
print_matrix [lindex $demo 1] "%.1f"</syntaxhighlight> |
||
Output: |
Output: |
||
<pre> |
<pre> |
||
Line 3,615: | Line 3,615: | ||
=={{header|VBA}}== |
=={{header|VBA}}== |
||
{{trans|Phix}}< |
{{trans|Phix}}<syntaxhighlight lang="vb">Option Base 1 |
||
Private Function vtranspose(v As Variant) As Variant |
Private Function vtranspose(v As Variant) As Variant |
||
'-- transpose a vector of length m into an mx1 matrix, |
'-- transpose a vector of length m into an mx1 matrix, |
||
Line 3,727: | Line 3,727: | ||
Debug.Print "Q * R" |
Debug.Print "Q * R" |
||
pp matrix_mul(q, r_) |
pp matrix_mul(q, r_) |
||
End Sub</ |
End Sub</syntaxhighlight>{{out}} |
||
<pre>A |
<pre>A |
||
12, -51, 4, |
12, -51, 4, |
||
Line 3,753: | Line 3,753: | ||
2, 0, 3, </pre> |
2, 0, 3, </pre> |
||
Least squares |
Least squares |
||
< |
<syntaxhighlight lang="vb">Public Sub least_squares() |
||
x = [{0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10}] |
x = [{0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10}] |
||
y = [{1, 6, 17, 34, 57, 86, 121, 162, 209, 262, 321}] |
y = [{1, 6, 17, 34, 57, 86, 121, 162, 209, 262, 321}] |
||
Line 3,782: | Line 3,782: | ||
Debug.Print Format(z(i), "0.#####"), |
Debug.Print Format(z(i), "0.#####"), |
||
Next i |
Next i |
||
End Sub</ |
End Sub</syntaxhighlight>{{out}} |
||
<pre>Least-squares solution: 1, 2, 3, </pre> |
<pre>Least-squares solution: 1, 2, 3, </pre> |
||
Line 3,789: | Line 3,789: | ||
{{libheader|Wren-matrix}} |
{{libheader|Wren-matrix}} |
||
{{libheader|Wren-fmt}} |
{{libheader|Wren-fmt}} |
||
< |
<syntaxhighlight lang="ecmascript">import "/matrix" for Matrix |
||
import "/fmt" for Fmt |
import "/fmt" for Fmt |
||
Line 3,889: | Line 3,889: | ||
Fmt.mprint(R, 8, 3) |
Fmt.mprint(R, 8, 3) |
||
System.print("\nQ * R:") |
System.print("\nQ * R:") |
||
Fmt.mprint(m, 8, 3)</ |
Fmt.mprint(m, 8, 3)</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
Line 3,916: | Line 3,916: | ||
=={{header|zkl}}== |
=={{header|zkl}}== |
||
< |
<syntaxhighlight lang="zkl">var [const] GSL=Import("zklGSL"); // libGSL (GNU Scientific Library) |
||
A:=GSL.Matrix(3,3).set(12.0, -51.0, 4.0, |
A:=GSL.Matrix(3,3).set(12.0, -51.0, 4.0, |
||
6.0, 167.0, -68.0, |
6.0, 167.0, -68.0, |
||
Line 3,923: | Line 3,923: | ||
println("Q:\n",Q.format()); |
println("Q:\n",Q.format()); |
||
println("R:\n",R.format()); |
println("R:\n",R.format()); |
||
println("Q*R:\n",(Q*R).format());</ |
println("Q*R:\n",(Q*R).format());</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre> |
<pre> |