From 629d1c00b2c04d0ea8c1ded376039b4f754e9bc0 Mon Sep 17 00:00:00 2001 From: Adrian Mariano Date: Fri, 28 Feb 2020 17:40:52 -0500 Subject: [PATCH] Added linear_solve() --- math.scad | 88 ++++++++++++++++++++++++++++++++++++++++++++++++++++++- 1 file changed, 87 insertions(+), 1 deletion(-) diff --git a/math.scad b/math.scad index 1d28ae6..ac99804 100644 --- a/math.scad +++ b/math.scad @@ -530,8 +530,94 @@ function product(v, i=0, tot=undef) = i>=len(v)? tot : product(v, i+1, ((tot==un function mean(v) = sum(v)/len(v); +// Section: Matrix math + +// Function: qr_factor() +// Usage: qr = qr_factor(A) +// Description: +// Calculates the QR factorization of the input matrix A and returns it as the list [Q,R]. This factorization can be +// used to solve linear systems of equations. +function qr_factor(A) = + let( + dim = array_dim(A), + m = dim[0], + n = dim[1] + ) + assert(len(dim)==2) + let( + qr =_qr_factor(A, column=0, m = m, n=m, Q=ident(m)), + Rzero = [for(i=[0:m-1]) [for(j=[0:n-1]) i>j ? 0 : qr[1][i][j]]] + ) + [qr[0],Rzero]; + +function _qr_factor(A,Q, column, m, n) = + column >= min(m-1,n) ? [Q,A] : + let( + x = [for(i=[column:1:m-1]) A[i][column]], + alpha = (x[0]<=0 ? 1 : -1) * norm(x), + u = x - concat([alpha],replist(0,m-1)), + v = u / norm(u), + Qc = ident(len(x)) - 2*transpose([v])*[v], + Qf = [for(i=[0:m-1]) [for(j=[0:m-1]) i