Anonymous user
QR decomposition: Difference between revisions
Updated D entry
(Updated D entry) |
|||
Line 639:
std.typecons, std.numeric, std.range, std.conv;
T[][] elementwiseMat(string op, T, U)(in T[][] A, in U B)
pure /*nothrow*/ if (is(U == T) || is(U == T[][])) {
static if (is(U == T[][]))
assert(A.length == B.length);
if (
return null;
auto R = new typeof(return)(A.length, A[0].length);
Line 658:
}
T[][] msum(T)(in T[][] A, in T[][] B) pure /*nothrow*/ {
return elementwiseMat!(q{ + }, T, T[][])(A, B);
}
T[][] msub(T)(in T[][] A, in T[][] B) pure /*nothrow*/ {
return elementwiseMat!(q{ - }, T, T[][])(A, B);
}
T[][] pmul(T)(in T[][] A, in T x) pure /*nothrow*/ {
return elementwiseMat!(q{ * }, T, T)(A, x);
}
T[][] pdiv(T)(in T[][] A, in T x) pure /*nothrow*/ {
return elementwiseMat!(q{ / }, T, T)(A, x);
}
bool isRectangular(T)(in T[][]
//return matrix.all!(r => r.length == mat[0].length)();
if (row.length != mat[0].length)
return false;
return true;
Line 689 ⟶ 690:
aux[k] = b[k][j];
foreach (i; 0 .. a.length)
result[i][j] =
}
return result;
}
Line 706 ⟶ 703:
}
T norm(T)(in T[][]
return
}
Line 759 ⟶ 755:
// Main routines ---------------
T[][] makeHouseholder(T)(in T[][] a) {
T[][] e = makeUnitVector!T(m);
T[][] u = msum(a, pmul(e, norm(a) * s));
Line 770 ⟶ 766:
Tuple!(T[][],"Q", T[][],"R") QRdecomposition(T)(T[][] A) {
T[][] Q = matId!T(m);
Line 804 ⟶ 800:
/// Solve an upper triangular system by back substitution.
T[][] solveUpperTriangular(T)(in T[][] R, in T[][] b) pure nothrow {
auto x = new T[][](n, 1);
Line 818 ⟶ 814:
/// Solve a linear least squares problem by QR decomposition.
T[][] lsqr(T)(T[][] A, in T[][] b) {
const qr = QRdecomposition(A);
return solveUpperTriangular(
slice2D(qr.R, 0, n-1, 0, n-1),
Line 836 ⟶ 832:
void main() {
// const (Q, R) = QRdecomposition(
const qr = QRdecomposition([[12.0, -51, 4],
[ 6.0, 167, -68],
[-4.0, 24, -41]]);
enum string form = "[%([%(%2.3f, %)]%|,\n %)]\n";
writefln(form, qr.R);
writeln(polyFit(x, y, 2));
}</lang>
Output:<pre>[[-0.
[-0.
[0.
[
[0.000, -0.000, -35.000]]
[[1], [2], [3]]</pre>
=={{header|Go}}==
{{trans|Common Lisp}}
|