QR decomposition: Difference between revisions

Content added Content deleted
m (→‎{{header|Phix}}: syntax coloured, improved output formatting a touch)
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;</lang>
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:
<lang Axiom>)abbrev package TESTP TestPackage
<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)</lang>
lsqr(a,y)</syntaxhighlight>
This can be called using:
This can be called using:
<lang Axiom>m := matrix [[12, -51, 4], [6, 167, -68], [-4, 24, -41]];
<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)</lang>
polyfit(x, y, 2)</syntaxhighlight>
With output in exact form:
With output in exact form:
<lang Axiom>qr m
<syntaxhighlight lang="axiom">qr m


+ 6 69 58 +
+ 6 69 58 +
Line 287: Line 287:


[1,2,3]
[1,2,3]
Type: Vector(AlgebraicNumber)</lang>
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.
<lang bbcbasic> *FLOAT 64
<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</lang>
ENDPROC</syntaxhighlight>
'''Output:'''
'''Output:'''
<pre>
<pre>
Line 406: Line 406:


=={{header|C}}==
=={{header|C}}==
<lang C>#include <stdio.h>
<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;
}</lang>
}</syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>
Line 626: Line 626:
{{libheader|Math.Net}}
{{libheader|Math.Net}}


<lang csharp>using System;
<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);
}
}
}</lang>
}</syntaxhighlight>


{{out}}
{{out}}
Line 677: Line 677:


=={{header|C++}}==
=={{header|C++}}==
<lang cpp>/*
<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:
<lang lisp>(defun sign (x)
<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:
<lang lisp>
<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:


<lang lisp>(qr #2A((12 -51 4) (6 167 -68) (-4 24 -41)))
<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))</lang>
( 0.0 0.0 -35.0))</syntaxhighlight>


Example 2, [[Polynomial regression]]:
Example 2, [[Polynomial regression]]:


<lang lisp>(defun polyfit (x y n)
<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))</lang>
x))</syntaxhighlight>


<lang lisp>;; Finally use the data:
<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))</lang>
#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]].
<lang d>import std.stdio, std.math, std.algorithm, std.traits,
<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;
}</lang>
}</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#}}==
<lang fsharp>
<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]''.


<lang fortran>program qrtask
<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</lang>
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.
<lang go>package main
<syntaxhighlight lang="go">package main


import (
import (
Line 1,727: Line 1,727:
}
}
return x
return x
}</lang>
}</syntaxhighlight>
Output:
Output:
<pre>
<pre>
Line 1,746: Line 1,746:


===Library QR, gonum/matrix===
===Library QR, gonum/matrix===
<lang go>package main
<syntaxhighlight lang="go">package main


import (
import (
Line 1,789: Line 1,789:
}
}
return x
return x
}</lang>
}</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
<lang haskell>
<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===
<lang haskell>import 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):<lang j> QR =: 128!:0</lang>
'''Solution''' (built-in):<syntaxhighlight lang="j"> QR =: 128!:0</syntaxhighlight>
'''Solution''' (custom implementation): <lang j> mp=: +/ . * NB. matrix product
'''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.
)</lang>
)</syntaxhighlight>


'''Example''': <lang j> QR 12 _51 4,6 167 _68,:_4 24 _41
'''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|
+-----------------------------+----------+</lang>
+-----------------------------+----------+</syntaxhighlight>


'''Example''' (polynomial fitting using QR reduction):<lang j> X=:i.# Y=:1 6 17 34 57 86 121 162 209 262 321
'''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</lang>
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'''.


<lang java>import Jama.Matrix;
<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);
}
}
}</lang>
}</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'''.


<lang java>import cern.colt.matrix.impl.DenseDoubleMatrix2D;
<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());
}
}
}</lang>
}</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'''.


<lang java>import java.util.Locale;
<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:
}
}
}
}
}</lang>
}</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'''.


<lang java>import org.la4j.Matrix;
<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]);
}
}
}</lang>
}</syntaxhighlight>


{{out}}
{{out}}
Line 2,104: Line 2,104:
=={{header|Julia}}==
=={{header|Julia}}==
Built-in function
Built-in function
<lang julia>Q, R = qr([12 -51 4; 6 167 -68; -4 24 -41])</lang>
<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}}==


<lang Maple>with(LinearAlgebra):
<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;</lang>
R;</syntaxhighlight>


{{out}}
{{out}}
Line 2,149: Line 2,149:


=={{header|Mathematica}}/{{header|Wolfram Language}}==
=={{header|Mathematica}}/{{header|Wolfram Language}}==
<lang Mathematica>{q,r}=QRDecomposition[{{12, -51, 4}, {6, 167, -68}, {-4, 24, -41}}];
<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</lang>
0 0 35</syntaxhighlight>


=={{header|MATLAB}} / {{header|Octave}}==
=={{header|MATLAB}} / {{header|Octave}}==
<lang Matlab> A = [12 -51 4
<syntaxhighlight lang="matlab"> A = [12 -51 4
6 167 -68
6 167 -68
-4 24 -41];
-4 24 -41];
[Q,R]=qr(A) </lang>
[Q,R]=qr(A) </syntaxhighlight>
Output:
Output:
<pre>Q =
<pre>Q =
Line 2,180: Line 2,180:


=={{header|Maxima}}==
=={{header|Maxima}}==
<lang maxima>load(lapack)$ /* This may hang up in wxMaxima, if this happens, use xMaxima or plain Maxima in a terminal */
<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 */</lang>
/* Note: the lapack package is a lisp translation of the fortran lapack library */</syntaxhighlight>
For an exact or arbitrary precision solution:<lang maxima>load("linearalgebra")$
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));</lang>Then we have the examples:<lang maxima>(%i) [q,r] : qr(a);
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 ]</lang>
[ 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.
<lang Nim>import math, strformat, strutils
<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)</lang>
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 parigp>matqr(M)</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.
<lang perl>use strict;
<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;</lang>
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]]
<!--<lang Phix>(phixonline)-->
<!--<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>
<!--</lang>-->
<!--</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.
<lang python>#!/usr/bin/env python3
<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))</lang>
print('\npolyfit:\n', polyfit(x, y, 2))</syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>
Line 2,758: Line 2,758:


=={{header|R}}==
=={{header|R}}==
<lang r># R has QR decomposition built-in (using LAPACK or LINPACK)
<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)</lang>
coef(m)</syntaxhighlight>


=={{header|Racket}}==
=={{header|Racket}}==


Racket has QR-decomposition builtin:
Racket has QR-decomposition builtin:
<lang racket>
<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:
<lang racket>
<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:
<lang racket>
<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 perl6># sub householder translated from https://codereview.stackexchange.com/questions/120978/householder-transformation
<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");
}</lang>
}</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.


<lang Rascal>import util::Math;
<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>
};</lang>
};</syntaxhighlight>


Example using visualization
Example using visualization
Line 3,174: Line 3,174:


=={{header|SAS}}==
=={{header|SAS}}==
<lang sas>/* See http://support.sas.com/documentation/cdl/en/imlug/63541/HTML/default/viewer.htm#imlug_langref_sect229.htm */
<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
*/</lang>
*/</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)].
<lang Scala>import java.io.{PrintWriter, StringWriter}
<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))


}</lang>
}</syntaxhighlight>


=={{header|SequenceL}}==
=={{header|SequenceL}}==
{{trans|Go}}
{{trans|Go}}
<lang sequencel>import <Utilities/Math.sl>;
<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] );</lang>
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:
<lang sml>signature RADCATFIELD = sig
<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</lang>
end</syntaxhighlight>
We can then show the examples:<lang sml>structure RealRadicalCategoryField : RADCATFIELD = struct
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</lang>
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.


<lang stata>mata
<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 |
+----------------------+</lang>
+----------------------+</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}}
<lang tcl>package require Tcl 8.5
<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]
}</lang>
}</syntaxhighlight>
Demonstrating:
Demonstrating:
<lang tcl>set demo [qrDecompose {{12 -51 4} {6 167 -68} {-4 24 -41}}]
<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"</lang>
print_matrix [lindex $demo 1] "%.1f"</syntaxhighlight>
Output:
Output:
<pre>
<pre>
Line 3,615: Line 3,615:


=={{header|VBA}}==
=={{header|VBA}}==
{{trans|Phix}}<lang vb>Option Base 1
{{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</lang>{{out}}
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
<lang vb>Public Sub 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</lang>{{out}}
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}}
<lang ecmascript>import "/matrix" for Matrix
<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)</lang>
Fmt.mprint(m, 8, 3)</syntaxhighlight>


{{out}}
{{out}}
Line 3,916: Line 3,916:


=={{header|zkl}}==
=={{header|zkl}}==
<lang zkl>var [const] GSL=Import("zklGSL"); // libGSL (GNU Scientific Library)
<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());</lang>
println("Q*R:\n",(Q*R).format());</syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>