74 lines
2.5 KiB
MQL5
74 lines
2.5 KiB
MQL5
|
//+------------------------------------------------------------------+
|
||
|
//| MatrixSVD.mq5 |
|
||
|
//| Copyright 2022, MetaQuotes Ltd. |
|
||
|
//| https://www.mql5.com |
|
||
|
//+------------------------------------------------------------------+
|
||
|
|
||
|
//+------------------------------------------------------------------+
|
||
|
//| Script program start function |
|
||
|
//+------------------------------------------------------------------+
|
||
|
void OnStart()
|
||
|
{
|
||
|
matrix a = {{0, 1, 2, 3, 4, 5, 6, 7, 8}};
|
||
|
a = a - 4;
|
||
|
a.Reshape(3, 3);
|
||
|
Print("matrix a \n", a);
|
||
|
|
||
|
// run SVD-decomposition:
|
||
|
|
||
|
matrix U, V;
|
||
|
vector singular_values;
|
||
|
a.SVD(U, V, singular_values);
|
||
|
Print("U \n", U);
|
||
|
Print("V \n", V);
|
||
|
Print("singular_values = ", singular_values);
|
||
|
|
||
|
// check the decomposition by equality U * singular diagonal * V = A.
|
||
|
|
||
|
matrix matrix_s;
|
||
|
matrix_s.Diag(singular_values);
|
||
|
Print("matrix_s \n", matrix_s);
|
||
|
matrix matrix_vt = V.Transpose();
|
||
|
Print("matrix_vt \n", matrix_vt);
|
||
|
matrix matrix_usvt = (U.MatMul(matrix_s)).MatMul(matrix_vt);
|
||
|
Print("matrix_usvt \n", matrix_usvt);
|
||
|
|
||
|
// compare original and rsulting matrices for discrepancies
|
||
|
|
||
|
ulong errors = (int)a.Compare(matrix_usvt, 1e-9);
|
||
|
Print("errors=", errors);
|
||
|
}
|
||
|
//+------------------------------------------------------------------+
|
||
|
/*
|
||
|
|
||
|
matrix a
|
||
|
[[-4,-3,-2]
|
||
|
[-1,0,1]
|
||
|
[2,3,4]]
|
||
|
U
|
||
|
[[-0.7071067811865474,0.5773502691896254,0.408248290463863]
|
||
|
[-6.827109697437648e-17,0.5773502691896253,-0.8164965809277256]
|
||
|
[0.7071067811865472,0.5773502691896255,0.4082482904638627]]
|
||
|
V
|
||
|
[[0.5773502691896258,-0.7071067811865474,-0.408248290463863]
|
||
|
[0.5773502691896258,1.779939029415334e-16,0.8164965809277258]
|
||
|
[0.5773502691896256,0.7071067811865474,-0.408248290463863]]
|
||
|
singular_values = [7.348469228349533,2.449489742783175,3.277709923350408e-17]
|
||
|
|
||
|
matrix_s
|
||
|
[[7.348469228349533,0,0]
|
||
|
[0,2.449489742783175,0]
|
||
|
[0,0,3.277709923350408e-17]]
|
||
|
matrix_vt
|
||
|
[[0.5773502691896258,0.5773502691896258,0.5773502691896256]
|
||
|
[-0.7071067811865474,1.779939029415334e-16,0.7071067811865474]
|
||
|
[-0.408248290463863,0.8164965809277258,-0.408248290463863]]
|
||
|
matrix_usvt
|
||
|
[[-3.999999999999997,-2.999999999999999,-2]
|
||
|
[-0.9999999999999981,-5.977974170712231e-17,0.9999999999999974]
|
||
|
[2,2.999999999999999,3.999999999999996]]
|
||
|
errors=0
|
||
|
|
||
|
*/
|
||
|
//+------------------------------------------------------------------+
|