least squares solver for MxN matrices using QR householder algorithm

This commit is contained in:
Bart Slinger
2018-09-18 09:39:17 +02:00
committed by Beat Küng
parent dc3af80977
commit 0009328257
5 changed files with 238 additions and 0 deletions
+1
View File
@@ -17,6 +17,7 @@ set(tests
helper
hatvee
copyto
least_squares
)
add_custom_target(test_build)
+69
View File
@@ -0,0 +1,69 @@
#include "test_macros.hpp"
#include <matrix/math.hpp>
using namespace matrix;
int test_4x3(void);
int test_4x4(void);
int main()
{
int ret;
ret = test_4x4();
if (ret != 0) return ret;
ret = test_4x3();
if (ret != 0) return ret;
return 0;
}
int test_4x3() {
// Start with an (m x n) A matrix
float data[12] = {20.f , -10.f , -13.f ,
17.f , 16.f , -18.f ,
0.7f, -0.8f, 0.9f,
-1.f , -1.1f, -1.2f};
Matrix<float, 4, 3> A(data);
float b_data[4] = {2.0, 3.0, 4.0, 5.0};
Vector<float, 4> b(b_data);
float x_check_data[3] = {-0.69168233f,
-0.26227593f,
-1.03767522f};
Vector<float, 3> x_check(x_check_data);
LeastSquaresSolver<float, 4, 3> qrd = LeastSquaresSolver<float, 4, 3>(A);
Vector<float, 3> x = qrd.solve(b);
TEST(isEqual(x, x_check));
return 0;
}
int test_4x4() {
// Start with an (m x n) A matrix
float data[16] = { 20.f , -10.f , -13.f , 21.f ,
17.f , 16.f , -18.f , -14.f ,
0.7f, -0.8f, 0.9f, -0.5f,
-1.f , -1.1f, -1.2f, -1.3f};
Matrix<float, 4, 4> A(data);
float b_data[4] = {2.0, 3.0, 4.0, 5.0};
Vector<float, 4> b(b_data);
float x_check_data[4] = { 0.97893433f,
-2.80798701f,
-0.03175765f,
-2.19387649f};
Vector<float, 4> x_check(x_check_data);
LeastSquaresSolver<float, 4, 4> qrd = LeastSquaresSolver<float, 4, 4>(A);
Vector<float, 4> x = qrd.solve(b);
TEST(isEqual(x, x_check));
return 0;
}
/* vim: set et fenc=utf-8 ff=unix sts=0 sw=4 ts=4 : */
+22
View File
@@ -124,4 +124,26 @@ for i in range(1,3):
A_pow = A_pow.dot(A)
print(eA_approx)
print('\nqr decomposition 4x4')
A = array([[20.0, -10.0, -13.0, 21.0], [ 17.0, 16.0, -18.0, -14], [0.7, -0.8, 0.9, -0.5], [-1.0, -1.1, -1.2, -1.3]])
b = array([[2.], [3.], [4.], [5.]])
x = scipy.linalg.lstsq(A,b)[0]
print('A:')
pprint(A)
print('b:')
pprint(b)
print('x:')
pprint(scipy.linalg.lstsq(A,b)[0])
print('\nqr decomposition 4x3')
A = array([[20.0, -10.0, -13.0], [ 17.0, 16.0, -18.0], [0.7, -0.8, 0.9], [-1.0, -1.1, -1.2]])
b = array([[2.], [3.], [4.], [5.]])
x = scipy.linalg.lstsq(A,b)[0]
print('A:')
pprint(A)
print('b:')
pprint(b)
print('x:')
pprint(x)
# vim: set et ft=python fenc=utf-8 ff=unix sts=4 sw=4 ts=8 :